How do I pass my own parameters to Middleware in Ravel 5.0?

Asked 2 years ago, Updated 2 years ago, 55 views

Ravel 5.1 introduces a new Middleware Parameters feature that allows you to pass your own parameters to Middleware, but due to PHP version requirements, you are forced to use Ravel 5.0.

I am trying to create Middleware this time and check if the logged in user has the permissions specified.
Specifically, I'm going to check it in the form of Auth::user()->hasRole('owner'), so I'm worried about how to tell middleware the parameters to pass to hasRole().

First of all, I borrow Request::route() and pass the parameters, but I can't predict what kind of problems will happen because it's not an officially prepared method.

The middleware is specified in __construct() on each controller.

public function__construct()
{
    $this->middleware('auth');
    Request::route()->setParameter('allowed_roles', ['owner']);
    $this->middleware('role');
}

The middleware contains the following:

class CheckRole
{
    public function handle($request,Closure$next)
    {
        $roles = $request->route()->parameter('allowed_roles', array());

        if(empty($roles)||$request->user()->hasRole($roles))
        {
            return$next($request);
        } else{
            return response('Unauthorized.',401);
        }
    }

}

In such a case, how is it standard to pass the parameters?
"Also, is ""Request::route()->setParameter()" good to use for these personal purposes?"
Thank you for your cooperation.

php laravel

2022-09-30 20:52

1 Answers

Laravel 5.0 uses the root filter functionality of Larvel 4.2.The root filter has the ability to specify parameters, so why don't you consider using this instead of middleware?

Specifying Filter Parameters

Route::filter('age', function($route,$request,$value)
{
    //
});

Route::get('user', array('before'=>'age:200', function()
{
    return 'Hello World';
}));

Reference URL
http://laravel.com/docs/4.2/routing#route-filters
http://laravel.com/docs/5.0/upgrade#upgrade-5.0

Middleware came out as an alternative to root filters in v5.0, but I don't think it's good to use root filters for parameters...

Can I use Request::route()->setParameter() for these personal purposes?

I don't think it's the original usage.If you just look at the code in this part, you can't read what it is for.It's like it's only when you look at the code in middleware that people understand it.If it does not affect other processing and it is judged that there is no problem if it is supplemented by comments, isn't it okay to use it?This will be up to you.


2022-09-30 20:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.