How to maintain load relationships for one eloquent object?

I have this model Comment

with attitude.

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

      

In my controller:

public function store(Request $request)
{
    $comment = $this->dispatch(
        new StoreCommentCommand($request->body, Auth::user()->id, $request->post_id)
    );

    return $comment;
}

      

When I return $comment

I also want a nested user object, how can I do that?

+3


source to share


2 answers


You need to use the with()

on Builder object whereas you are currently using on the eloquent object. This will be your working code.



    return Comment::with('user')->where('id', $comment->id)->first();

      

+2


source


Just download it ...



return $comment->with('user');

      

+1


source







All Articles