Exind
Exind

Reputation: 447

Laravel Eloquent Convert user_id to user info

I've some relationships in my Model classes.


Consume this relationship:
We've Post() model which store our posts data. Each post in this table has a user_id column that has one to many relationship with User() Mode (the author of the post)

class User extends Model {
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}
class Post extends Model {

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

So when i want to return my post with elequent, I'll get something like this:

{
    "user_id": 1,
    "title": "Foo name",
    "body": "Foo body",
},
{
    "user_id": 1,
    "title": "Bar name",
    "body": "another Bar body",
}

But i want to get something like this:

{
    "user_id": 1,
    "user": {
        'name'=> 'John',
        'last'=> 'Maco',
     },
    "title": "Foo name",
    "body": "Foo body",
},
{
    "user_id": 1,
    "user": {
        'name'=> 'John',
        'last'=> 'Maco',
     },
    "title": "Bar name",
    "body": "another Bar body",
}

Upvotes: 1

Views: 863

Answers (1)

N69S
N69S

Reputation: 17206

You need to declare the relation from Post to User

Post.php

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Then you will be able to load the user with every post like @dparoli commented

$post = Post::with('user')->get();

Upvotes: 2

Related Questions