Jump to content

laravel 5.4 with condition in model


mstdmstdd

Recommended Posts

 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! 

Link to comment
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 comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.