Jump to content

laravel 5.4 with condition in model

Recommended Posts

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)

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 )

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 ?



Link to post
Share on other sites

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?

Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.