Reputation: 578
Let's say I have a route pointing to middleware;
Route::get("/user/{id}", ['middleware' => 'auth', function ($id) {
}]);
And my middleware code is as follows:
public function handle($request, Closure $next)
{
return $next($request);
}
If I want to use $id
in the middleware, how do I do that?
Upvotes: 30
Views: 62002
Reputation: 11
On this I move the auth()->check() to be handled by the middleware the would format the code to be something like
<?php
namespace App\Http\Middleware;
use Closure;
class Authentication
{
public function handle($request, Closure $next, $role)
{
if (!auth()->user()->hasRole($role)) {
return redirect('login');
}
return $next($request);
}
}
Upvotes: 0
Reputation: 13693
In you case you cannot pass $id
into the middleware.
Generally you can pass parameters to middleware via using :
symbol like this:
Route::get('user/{id}', ['middleware' => 'auth:owner', function ($id) {
// Your logic here...
}]);
And get the passed parameter into middleware method like this:
<?php
namespace App\Http\Middleware;
use Closure;
class Authentication
{
public function handle($request, Closure $next, $role)
{
if (auth()->check() && auth()->user()->hasRole($role)) {
return $next($request);
}
return redirect('login');
}
}
Note that the
handle()
method, which usually only takes a$request
and a$next closure
, has athird parameter
, which is our middleware parameter.If you passed in multiple parameters like
auth:owner,subscription
to your middleware call in the route definition, just add more parameters to your handle method which will look like this -handle($request, Closure $next, $role,$subscription)
Upvotes: 53
Reputation: 17658
You can use one of the following method to access the route parameter in a middleware:
First Method
$request->route()->parameters();
This method will return an array of all the parameters.
Second Method
$request->route('parameter_name');
Here parameter_name
refers to what you called the parameter in the route.
Upvotes: 40