Category : #laravel
Tags : #laravel, #laravel middleware
In this tutorial, I will show how to pass parameters in Laravel middleware. You already know that Laravel middleware accepts by default two parameters one is $request and the other is the $next parameter. But we can also pass one or more parameters in Laravel middleware.
Passing Parameters in Middleware Laravel
Additional extra middleware parameters can be passed to the middleware after the $next
an argument like: See the below example code to understand:
app\Http\Middleware\EnsureUserHasRole.php
<?php
namespace App\Http\Middleware;
use Closure;
class EnsureUserHasRole
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $role
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
}
return $next($request);
}
}
Now the Middleware parameters must be specified when defining the route by separating the middleware name and parameters with a :
and if Multiple then all the parameters should be delimited by commas:
routes/web.php
Route::put('/post/{id}', function ($id) {
//
})->middleware('role:editor');
Read also: Complete Explanation With Example On Laravel Middleware
Hope it can help you.