alex_hill's avatar

Route model binding not working

I have the following route

Route::resource('users', 'BuilderController');

And in BuilderController the following method

public function edit(Builder $users)
{
        dd($users);

}

When I hit up URL.com/users/3/edit the dumped user is blank - no attributes. However the following code shows the correct user, so the "3" is being passed through to the method:

public function edit($users)
{
        dd(Builder::find($users));

}

I have the facade included, as proven by the second code block working.

I have recently changed the route from /admins/3/edit and using AdminController to BuilderController, so there might be some issue in there.

Any suggestions on why the first instance is not working?

0 likes
5 replies
EventFellows's avatar

Try it with $user instead of $users. Or change the typehint to User (must match the model name, of course)

I believe either the variables name or the typhints name must exactly match the model you want to bind it to (there might also be a way to overwrite this convention thought)

Edit:

https://laravel.com/docs/5.4/routing#implicit-binding

or see the explicit binding in the following paragraph

2 likes
alex_hill's avatar

hmm, the problem is I already have a User model, for a different purpose (Builder is like Admin), but I still want the URL structure to be /users/x/edit . I could be explicit in my routes instead of using a resource route I guess. Why cant I have everything???

Thanks for the response @EventFellows

kenny11's avatar

I think you need to type-hint a user model to make it work or you can use route model binding.

Route::bind('users', function($users)
        {
            return \App\Builder::find($users);
        });

and then in your controller

public function edit(Builder $users)
{
        dd($users);

}
shopsaloon's avatar

For me, adding the web middleware to my route solved the problem.

8 likes
diveshc22's avatar
Route::resource('users', UsersController::class);


 public function update(UpdateUserRequest $request, User $user)
    {
		 	$user->update($request->all());
			return reponse()->noContent();
	}

Please or to participate in this conversation.