3

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 ])
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
Renuga
  • 45
  • 6
  • What is the problem, you always get 404? – thefallen Jan 11 '19 at 08:01
  • @thefallen I am gettinng the index page and not the show page, you can see I am missing the model there. – Renuga Jan 11 '19 at 09:01
  • I would instead move this logic into a middleware or in the controller method, because with route binding this thing is hidden and is like magic, but the bad kind of it. – thefallen Jan 11 '19 at 09:12
  • @thefallen what will be the proper way to get route model binding for pivote models? – Renuga Jan 11 '19 at 09:19
  • You just bind it to the correct model class and in the middleware or controller you validate that they have a relation between each other. – thefallen Jan 11 '19 at 09:21
  • @thefallen I have done it in controller like `public function show(Apartment $apartment, Association $association, AssociationUser $associationUser) ` but it does not seems to be working, it will a great help, if you can give me some link or provit a minimal snipet to achieve it. – Renuga Jan 11 '19 at 09:27

1 Answers1

1

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

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105