How to get a field from a sub-relation in laravel?

Member

by dana , in category: Third Party Scripts , 10 months ago

How to get a field from a sub-relation in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 10 months ago

@dana 

You can get a field from a sub-relation in Laravel by using the with() method when querying the main model.


For example, if you have a User model that has a relationship with a Post model, and each post has a title field, you can get the title of the post for a specific user like this:

1
2
3
4
5
$user = User::with('posts')->find($userId);

foreach ($user->posts as $post) {
    echo $post->title;
}


In this example, we are eager loading the posts relationship using the with() method, and then accessing the title field of each post for the specified user.


Alternatively, you can use the pluck() method to get a specific field from the sub-relation like this:

1
$titles = User::find($userId)->posts->pluck('title');


This will return a collection of all the title fields for the posts related to the specified user.

Related Threads:

How to get select field in model using laravel?
How to render all data in relation in laravel?
How to use recursive relation in laravel?
How to make a relation in laravel in model?
How to chain eloquent relation in route in laravel?
How to make a relation between 2 tables in laravel?