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++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -