@bobeta You could use middleware parameters.
Middleware or / and roles
I have several roles in my middlewares declared. When authenticating one of them in the controller, I do the following:
public function __construct()
{
$this->middleware('admin', ['except' => 'getLogin']);
}
If I would want it to accept both 'admin' and 'member' roles, how can I make that happen in the syntax? I suppose it would be better if I made another middleware that has both of those roles in them, but is there any other way? Thanks!
@bobeta Assign the middleware with a parameter like it is specified in the documentation. Example:
$this->middleware( 'role:admin', ['except' => 'getLogin'] );
role is the name of the middleware (instead of your current admin).
In the middleware class use the following:
public function handle( $request, Closure $next, $role )
Now, the role label admin will be available in the variable $role. So you just need to perform the check if the current user has the specified role.
But, you want to check for multiple roles. I don't think you can specify an array of values in the call to $this->middleware() (others might jump in if it's possible) so there are several roads you can travel, e.g.:
- Use labels for role combinations that you allow separated by a delimiter (e.g.
admin.member) and explode them. - Use a bit mask to specify the role combinations.
- Use multiple parameters explicitly or utilize
func_get_args(). Example:
$this->middleware( 'role:admin,member', ['except' => 'getLogin'] );
public function handle( $request, Closure $next, $role1, $role2 )
Now $role1 will contain admin and $role2 will contain member.
Others might contribute more elegant options.
Please or to participate in this conversation.