So I am trying to return an array of objects with my Laravel collection using the following code:
/**
 * View a user's chat rooms.
 *
 * return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory\
 */
public function viewChatRooms()
{
    $user = Auth::user(); // @var User $user
    $username = $user->username;
    $rooms = Room::with('messages')->get()
                    ->filter(function ($val) use ($username){
                        foreach ($val->users as $user) {
                            if($user === $username){
                                return $val;
                            }
                        }
    });
    return response(['rooms' => $rooms]);
}
Instead of returning an array of objects, the response returns the following:
{
    "rooms": {
        "0": {...},
        "3": {...}
    }
}
This is the desired result:
{
    "rooms": [
        {...},
        {...}
    ]
}
Kind of stumped by this, could some one guide me in the right direction?
You Can use array_value function of PHP when returning response like this:
return response()->json([
    'rooms' => array_values($rooms->toArray())
]);
Laravel Collection Methods for Getting only values of Collection
https://laravel.com/docs/5.8/collections#method-values
So
return response()->json([
    'rooms' => $rooms->values()->toArray()
]);
                        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