How to Route Model Binding Injection through a Middleware with Laravel

If we want to perform any kind of change or improve the search before binding our model into a route, we could do the following:

  • Create a Middleware for your routes
$ php artisan make:middleware MyBindingModelMiddleware
  • Register the Middleware into our Kernel.php

Kernel.php

protected $routeMiddleware = [  
        ...
        'request.bind.model.user' => 'Motty\Http\Middleware\MyBindingModelMiddleware',
    ];
  • Link the middleware to our desired routes

You can do this in different ways:

  • Register the middleware into the Controller __construct
  • Register the middleware into our route.php file like a filter

This last one is the option I have choosen, as you can see below:

...
Route::group(['middleware' => ['request.sanitize', 'request.bind.model.user']], function () {  
    Route::get('settings', ['uses' => 'SettingsController@index', 'as' => 'settings.index']);
}
...
  • Perform the changes or improve the search and bind the model

MyBindingModelMiddleware.php

public function handle($request, Closure $next)  
{
    if ($request->has('id') && $request->has('space')) {
       // perform a specific search
        $user = $this->userRepository->getByIdAndSpace($request->get('id'), $request->get('space'));
        // do some needed changes
        $user->fullName = $user->forename . ' ' . $user->surname;
        $request->route()->setParameter('Motty\Entities\User', $user);
    }
}

This is the bit that do the magic:

$request->route()->setParameter('Motty\Entities\User', $user);

  • And the last step use our model instance easily from our controllers, like so:
public function index(User $user)  
{
...

Note

We could bind more than one model at the time

$request->route()->setParameter('Motty\Entities\User', $user);
$request->route()->setParameter('Motty\Entities\Space', $space);
public function index(User $user, Space $space) {  
...

Resources