13

Just as per the title. Default api middleware in Laravel 5.6 is listed in Kernel.php as:

protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

I'd appreciate a layman's explanation of what bindings does, which I can't find anywhere.

It uses the SubstituteBindings class which has the handle method:

public function handle($request, Closure $next)
{
    $this->router->substituteBindings($route = $request->route());
    $this->router->substituteImplicitBindings($route);
    return $next($request);
}

Though I still don't follow what it does.

Inigo
  • 8,110
  • 18
  • 62
  • 110
  • I started reading that after posting the question- thanks. But I'm still unclear how this relates to the binding Middleware which that short section of the docs doesn't mention. Do I have to pass all routes through this middleware before I can use Route Model Binding? That section of the docs seems to suggest otherwise. – Inigo Jul 31 '18 at 12:02

2 Answers2

15

I had the same question, and was able to find this:

"Route model binding is now accomplished using middleware. All applications should add the Illuminate\Routing\Middleware\SubstituteBindings to your web middleware group in your app/Http/Kernel.php file:

\Illuminate\Routing\Middleware\SubstituteBindings::class,

You should also register a route middleware for binding substitution in the $routeMiddleware property of your HTTP kernel:

'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, ..."

which can be found on this page - https://laravel.com/docs/5.3/upgrade

The above answer was originally from this source - https://stackoverflow.com/a/47784205/3089840

So it sounds to me like the bindings middleware is just a shortcut term for \Illuminate\Routing\Middleware\SubstituteBindings::class - If this is correct, I'm not sure why Laravel doesn't use the same terminology in both the web and the api arrays in Kernel.php. It seems kind of inconsistent and confusing to use \Illuminate\Routing\Middleware\SubstituteBindings::class in the web array and bindings in the api array.

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
Bryan Miller
  • 3,262
  • 4
  • 27
  • 51
10

I think the thing that you're asking for is this https://laravel.com/docs/5.7/routing#route-model-binding

Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

It binds the User model right away.

Mladen Janjetovic
  • 13,844
  • 8
  • 72
  • 82