Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Collection - Return Array of Objects

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?

like image 943
Solomon Antoine Avatar asked Sep 03 '19 03:09

Solomon Antoine


1 Answers

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()
]);
like image 148
Priyanka khullar Avatar answered Oct 07 '22 09:10

Priyanka khullar