Can I Filter Laravel Collection Using Where Method And Some Other Model's Method?

- 1 answer

I have a model called Billboard. In this model I wrote a method isDisplayable().

   public function isDisplayable()
      if  (/* Logic to determine if billboard is displayable */)
        return true;
     return false;

I want the collection of Billboards that are only displayable. Can I utilize Where method with isDisplayable()? or should I adopt some other approach?



If you already have the Collection, you can use the filter() method to filter out results based on your Model method:

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

If you want to use this logic on a query (before the Collection is even built), you can create a query scope on your Billboard model:

public function scopeDisplayable($query, $displayable = true)
    if ($displayable) {
        // modify $query to only get displayable items, e.g:
        $query->where('displayable', '=', 1);
    } else {
        // modify $query to only get non-displayable items, e.g:
        $query->where('displayable', '=', 0);

// use your new query scope like any other method on the query builder:

// displayable billboards:
$billboards = Billboard::displayable()->get();

// non-displayable billboards:
$billboards = Billboard::displayable(false)->get();