api: Route Model Binding not working correctly with Laravel 5.3

I am having an issue with route model binding on my dingo (dev-master w/ L5.3 support) specific routes. On my Laravel web routes it works fine and returns the model with the correct data. It also works on Laravel 5.2.

routes/api.php

$api->get('users/{user}', ['as' => 'users.show', 'uses' => 'UserController@show']);

UserController.php

public function show(User $user)
{
    dd($user);

    return $this->response->item($user, new UserTransformer);
}

The $user object is empty. I have tried with another controller too with the same results.

I can only get it to work by using first(), which defeats the purpose of model binding.

public function show(User $user)
{
    $data = $user->first();

    return $this->response->item($data, new UserTransformer);
}

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 4
  • Comments: 32

Most upvoted comments

Add bindings middleware to your route as such:

$api->group(['middleware' => 'bindings'], function($api){
    $api->get('users/{user}', ['as' => 'users.show', 'uses' => 'UserController@show']);
});

For those who find this solution not working - check your Kernel.php, $routeMiddleware should contain: 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

I found that must to add bindings middleware in the same route group that added auth.api middleware instead adding it to each sub routes separately.
means like this :

	$api->group(['middleware' => 'api.auth|bindings'], function ($api) {
            });

Does your api middleware group have assigned ‘bindings’? In app/Http/Kernel.php:

// For web routes
'web' => [
           ...
            \Illuminate\Routing\Middleware\SubstituteBindings::class
        ],
// For api routes
'api' => [
            'throttle:60,1',
            'bindings'
        ],

This change should be on the Upgrade Guide from 5.2 -> 5.3!

this is giving me null

Yes this bindings route middleware is there and still I am not able to get model object. Its working for other controllers,

I am using laravel 5.3