Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "bindings" middleware do in Laravel 5.6?

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.

like image 545
Inigo Avatar asked Jul 31 '18 11:07

Inigo


2 Answers

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.

like image 90
Bryan Miller Avatar answered Nov 14 '22 10:11

Bryan Miller


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.

like image 10
Mladen Janjetovic Avatar answered Nov 14 '22 10:11

Mladen Janjetovic