Use route model binding on Middlewares in Laravel

Ariel Mejia

July 18th, 2020 - 1 min read

Route Model Binding is a feature that allows the Laravel Container to resolve a model instance by a route param automatically.

Create a middleware

php artisan make:middleware UserMiddleware

For the sake of simplicity in this example we are going to check if the user has a specific name, if not it will redirect back with a status flash message

In directory App/Http/Middleware

public function handle($request, Closure $next)
{
    // 1 way to get the model from route model binding
    //$condition = Route::current()->parameters()->name === 'John Doe';
    // 2 way to get the model from route model binding
    //$condition = $request->name === 'John Doe'
    // 3 way to get the model from route model binding
    $condition = $request->route('user')->name === 'John Doe';
    if ($condition) 
    {
         return redirect()
             ->back()
             ->with('status', 'user is not the admin');
    }
    return $next($request);
}

Route model binding only works if route has the model param /{user} and both names matches


In order to use a custom param name Laravel provides different ways to customize route model binding the easiest way is to add the method params(['user' => 'customParam']) to the current route

Thanks for reading!


Ariel Mejia Illustration

Ariel Mejia

Laravel Senior Developer

Engineer with 7+ years of experience working in backend & frontend technologies
Open Source Maintainer of packages for Laravel community.

Stay up with Laravel

Sign up & get tips and tricks

You'll get monthly updates regarding my most recent articles and products.