Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search value deeply nested within a Laravel Collection

I have an Eloquent Collection just like this (dumped):

Collection {#788 ▼
  #items: array:3 [▼
    0 => Rating {#787 ▼
      #table: "ratings"
      +timestamps: false
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      #attributes: array:3 [▼
        "id" => 1
        "rating" => "50"
        "type" => "min"
      ]
      #original: array:3 [▶]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => Rating {#786 ▶}
    2 => Rating {#785 ▶}
  ]
}

In one of my views, I need to show only the Ratings with 'max' type and I am trying to filter the collection without success until now. My tries so far:

if ($ratings && $ratings -> search('max') != false)

OR

if ($ratings && $ratings -> contains('max'))

So... What is the smart and eloquent way of achieving this?

Thanks in advance.

like image 792
andcl Avatar asked Mar 16 '17 19:03

andcl


2 Answers

You can use the where method: https://laravel.com/docs/5.4/collections#method-where

$filtered_ratings = $ratings->where('type', 'max');
like image 99
Brian Glaz Avatar answered Nov 10 '22 23:11

Brian Glaz


You could also use the filter() method on the collection.

return $collection->filter(function ($value, $key) {
    if($value->type == 'max'){
      return $value;
    }    
});
like image 39
Yat23 Avatar answered Nov 10 '22 21:11

Yat23