Search code examples
laraveleloquentlaravel-8

How to access methods inside custom pivot model


I'm using Laravel 8, and having many-to-many relationship using custom pivot model as explained here in the documentation. However, I don't know how can I access the methods that I have created inside the custom pivot model.

Let's say, using the example provided in the doc, I created some methods inside the RoleUser model. My question is: how can I access those methods from Role model, from something like Role::find(1)->users() ? Is it possible?

Thank you in advance!


Solution

  • Same as accessing any attribute from pivot.

    https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

    use App\Models\User;
     
    $user = User::find(1);
     
    foreach ($user->roles as $role) {
        echo $role->pivot->methodInPivot();
    }