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

Member

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

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 6 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.