Filtering Eloquent collection data with $collection->filter()
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();
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'));
}
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();