mstdmstdd Posted April 14, 2017 Share Posted April 14, 2017 Hello,Here http://themsaid.com/laravel-query-conditions-20160425/There si an example of laravel 5.4 with condition in model : $results = DB::table('orders')->where('branch_id', Auth::user()->branch_id) ->if($request->customer_id, 'customer_id', '=', $request->customer_id) ->get(); I tried to make similar but using model : $clients = Client:: select( 'client_id', 'name', 'login', 'active_till_date' ) ->if ( $filter_only_active, 'is_active', '=', 'Y' ) ->orderBy( $order_by, $order_direction ) ->get(); and got error : BadMethodCallException in Builder.php line 2443: Call to undefined method Illuminate\Database\Query\Builder::if() which is the correct syntax ? I prefer working with model, not with DB...Also, I would like to use scope methods under if conditions... Is it possible ? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/303707-laravel-54-with-condition-in-model/ Share on other sites More sharing options...
dkub Posted April 14, 2017 Share Posted April 14, 2017 The if() method is not part of the core, so we may register it using a Macro: use Illuminate\Database\Query\Builder; Builder::macro('if', function ($condition, $column, $operator, $value) { if ($condition) { return $this->where($column, $operator, $value); } return $this; }); Have you done this? Quote Link to comment https://forums.phpfreaks.com/topic/303707-laravel-54-with-condition-in-model/#findComment-1545449 Share on other sites More sharing options...
NigelRel3 Posted April 17, 2017 Share Posted April 17, 2017 (edited) I'm not sure about some of these macros, I know it MAY make the code a bit more compact, but does it make it more maintainable? Edited April 17, 2017 by NigelRel3 Quote Link to comment https://forums.phpfreaks.com/topic/303707-laravel-54-with-condition-in-model/#findComment-1545535 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.