2557272
2557272

Reputation: 31

Laravel 4:: Returning models and its relationship

I would like to return the model and part of its relationship

EX::

User model

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

Comments model

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

Can I return all comments and the user's name associated with the comment?

The desired effect is

    $comment = Comments::find($id);
    $comment->user;
    return $comment;

This will return the one comment and the associated user full model. I just need the name of the user. And this does not works if I call Comments::all()

Thank you in advance.

Upvotes: 3

Views: 11320

Answers (1)

fideloper
fideloper

Reputation: 12293

You're looking for Eloquent's Eager Loading

Assuming your Comments model has a method user():

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

You should be able to do this in your controller:

$comments = Comments::with('user')->where('post_id', $post_id);

// Return JSON, as is Laravel's convention when returning 
// Eloquent model directly
return $comments;

You can do the opposite as well:

Assuming your User model has a method 'comments()', like so:

public function comments()
{
    return $this->hasMany('Comment');
}

Inside of your controller, you should be able to do the following, assuming your have the $id of the user available:

$user = User::with('comments')->find($id);

// Return JSON, as is Laravel's convention when returning 
// Eloquent model directly
return $user;

Upvotes: 9

Related Questions