Reputation: 1831
I need to remove items from a collection based on an attribute (Laravel 5.6).
$leagues = League::all();
foreach($leagues as $i => $L){
if($L->status == LeagueStatus::HIDDEN){
$leagues->forget($i); <<<<======== 1st attempt
unset($leagues[$i]); <<<<======== 2nd attempt
}
}
return response()->json($leagues->toArray());
Both methods removes the items correctly, but causes that response JSON comes as object:
{ <<<<======== ITS OBJECT WITH NUMBERED KEYS, NOT ARRAY
"0":{
"id":1,
"title":"test...
Correct JSON would be:
[ <<<<======== NORMAL ARRAY WITH OBJECTS
{
"id":1,
"title":"test...
Am I doing something wrong?
Upvotes: 0
Views: 56
Reputation: 50491
Use values
to get a new Collection with the keys reset to consecutive integers:
return response()->json($leagues->values());
Laravel 6.x Docs - Collections - Available Methods - values
Upvotes: 1
Reputation: 389
Just replace this
return response()->json($leagues->toArray());
to
return json_decode($leagues);
Upvotes: 0