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.
You can use the where method: https://laravel.com/docs/5.4/collections#method-where
$filtered_ratings = $ratings->where('type', 'max');
                        You could also use the filter() method on the collection.
return $collection->filter(function ($value, $key) {
    if($value->type == 'max'){
      return $value;
    }    
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With