Can I filter laravel collection using where method and some other Model's method? -


i have model called billboard. in model wrote method isdisplayable().

   public function isdisplayable()    {       if  (/* logic determine if billboard displayable */)         return true;      return false;    } 

i want collection of billboards displayable. can utilize where method isdisplayable()? or should adopt other approach?

if have collection, can use filter() method filter out results based on model method:

$billboards = billboard::all(); $filtered = $billboards->filter(function ($billboard, $key) {     // true keep; false remove     return $billboard->isdisplayable(); }); 

if want use logic on query (before collection built), can create query scope on billboard model:

public function scopedisplayable($query, $displayable = true) {     if ($displayable) {         // modify $query displayable items, e.g:         $query->where('displayable', '=', 1);     } else {         // modify $query non-displayable items, e.g:         $query->where('displayable', '=', 0);     } }  // use new query scope other method on query builder:  // displayable billboards: $billboards = billboard::displayable()->get();  // non-displayable billboards: $billboards = billboard::displayable(false)->get(); 

Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -