willard_macay's avatar

laravel eager load pivot relation

can I eager load pivot relation without installing a package?

0 likes
7 replies
LaryAI's avatar
Level 58

Yes, you can eager load pivot relations in Laravel without installing a package. You can use the withPivot() method in your model to specify the columns you want to retrieve from the pivot table. Here's an example:

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class)->withPivot('created_at', 'updated_at');
    }
}

In this example, we're eager loading the created_at and updated_at columns from the pivot table for the roles relationship.

Then, you can access the pivot data using the pivot attribute on the related model. For example:

$user = User::with('roles')->find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
    echo $role->pivot->updated_at;
}

This will output the created_at and updated_at values for each role that the user has.

dcx's avatar

Yes, if your model is setup with the relations as normal then you can still use the POST::with('comment') - for example..

willard_macay's avatar

@dcx What I mean is pivot relation like this

$carousel->pivot->fields

pivot relations with fields

dcx's avatar

@willard_macay when you load a many to many for example category with products the category_product pivot table only has 2 values category_id and product_id the full models are loaded so category::with('products') would return category (full model) and product(full model) so if you want a value you would say category->product->name

do you have extra columns in your pivot table?

dcx's avatar

i should say it would be returned with category->products[productA, productB]

dcx's avatar

@willard_macay just realized the same person as on the other thread i was on - i recommend for both topics this youtube channel, good quality and you'll search and find both this and the other topic discussed...you don't need extra package here..

https://www.youtube.com/@LaravelDaily

Please or to participate in this conversation.