How to user route model binding in Laravel for Pivot model

Viewed 610

Laravel v: 5.7

PHP v: 7.2.10

Route path is: admin/apartments/{apartment}/associations/{association}/association-users/{association_user}
Getting URL: http://127.0.0.1:8000/admin/apartments/1/associations/1/association-users

Pivot Model: AssociationUser

In App\Providers\RouteServiceProvider, I have added

public function boot()
    {
        parent::boot();

        Route::bind('association-user', function ($value) {
            return App\pivotes\AssociationUser::where('association_id', request()->route()->parameter('association')->id)->where('user_id', auth()->id())->first() ?? abort(404);
        });
    }

Route Creation

route('apartments.associations.association-users.show', ['apartment' => $associationUser->association->apartment, 'association' => $associationUser->association, 'association_user' => $associationUser ])
1 Answers

If I am not wrong association_user pivot table should have association_id and user_id and combination of both will be unique, so in your route there is already {association} model, so I believe you can use

public function getRouteKeyName()
{
    return 'user_id';
}

in you pivot model class so that user_id will come in your url and you will be having combination of association and user model.

You do not need

 Route::bind('association-user', function ($value) {
            return App\pivotes\AssociationUser::where('association_id', request()->route()->parameter('association')->id)->where('user_id', auth()->id())->first() ?? abort(404);
        }); 

in your App\Providers\RouteServiceProvider

Related