Returning multiple Laravel Eloquent models as JSON

My “user” model with a has-many relationship to an “image” model.

Returning just the user is as easy as “return Response::eloquent($user);”. I’d like to either return a JSON array of
{user: {id:…}, images: [{id:…},{id:…}]}
or, perhaps better,
{id:…, images: [{id:…},{id:…}]}

What’s the best way to arrange and ship these models? Should I

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The first thing you’ll need to do is make sure your models are set up correctly:

class Users extends Eloquent {

    public function images()
    {
        return $this->hasMany('Image');
    }

}

class Image extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}

Then in your route you should be able to do something like:

Route::any('userinfo/{$userId}', function($userId)
{
    return Response::json(User::with('images')->find($userId));

    //or

    return User::with('images')->find($userId)->toJson();
});

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply