Filtering Eloquent collection data with $collection->filter()

Solution 1:

The collection's filter method calls array_filter on the underlying array, which, according to the PHP docs, preserves the array keys. This then results in your array being converted to a JavaScript object instead of an array.

Call values() on your collection to reset the keys on the underlying array:

$filtered_collection = $collection->filter(function ($item) {
    return $item->isDog();
})->values();

Side note: in newer versions of Laravel, you can use a higher order message to shorten the above into this:

$filtered_collection = $collection->filter->isDog()->values();

Solution 2:

Just convert it to JSON with keeping in mind what the Laravel documentation states:

Note: When filtering a collection and converting it to JSON, try calling the values function first to reset the array's keys.

So the final code would be:

$filtered_collection->values()->toJson();

Solution 3:

Filtering from database could be done in this method also.

 //request the form value 
  $name=$request->name;
  $age=$request->age;
  $number=$request->phone;

 //write a query to filter
 $filter_result = DB::table('table_name')

 ->where('name', 'like', '%'.$name.'%')
 ->orWhere('age', 'like', '%'.$age.'%')
 ->orWhere('phone', 'like', '%'.$number.'%')

 ->get();

 if(is_null($filter_result)){
 return redirect()->back()->with('message',"No Data Found");

}else{
      return view('resultpage',compact('filter_result'));
}

Solution 4:

If you have eloquent collection array and you want to filter it from some attribute, you can try following filter to achieve this.

In my case, $reports is variable contain eloquent collection object. and i want to filter from this collection with id attribute.

$filter_id = $reports->filter(function ($item) {
   return $item->id==5;
})->first();

now you have $filter_id variable that contains object with id=5.

you can access all attribute of id=5, like $filter_id->attribute_name.