Here is my code :
public function list()
{
$users = User::with('group')->get()->toArray();
return response()->json([
'clients' => array_filter($users, function ($r) {
return $r['group']['name'] === 'client';
}),
'employes' => array(array_filter($users, function ($r) {
return $r['group']['name'] !== 'client';
})),
]);
}
Here is the response :
{
"clients": {
"2": {
"id": 3,
"name": "Client 1",
"email": "[email protected]",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"3": {
"id": 4,
"name": "Client 2",
"email": "[email protected]",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
},
"4": {
"id": 5,
"name": "Client 3",
"email": "[email protected]",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 4,
"group": {
"id": 4,
"name": "client"
}
}
},
"employes": [
[
{
"id": 1,
"name": "Alexis",
"email": "[email protected]",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 1,
"group": {
"id": 1,
"name": "admin"
}
},
{
"id": 2,
"name": "guest",
"email": "[email protected]",
"email_verified_at": null,
"created_at": null,
"updated_at": null,
"group_id": 2,
"group": {
"id": 2,
"name": "guest"
}
}
]
]
}
I tried to change the conditions of the array_filter. Sometimes I have an array, sometimes I have an object. I don't understand how this is determined
Stackoverflow tells me "It looks like your post is mostly code; please add some more details." So ... what details to add?
Thank you
clientsreturn has the first index of2, not0. I think you can just wraparray_filterwitharray_valuesto reset the indices.