php - Is there anyway to code such that I can define or condition in middleware? -
i have 3 roles in application. have condition in 2 roles can access same page. write below code.
in below code, sub plan1 , sub plan 2 roles.
route::group(['middleware' => ['web', 'auth', 'subplan1', 'subplan2']], function () { route::get('/parent-1-info', '\contactinfocontroller@parent1info')); });
if sub plan1, tries access page, 404 error because mentioned both middleware in same group.
is there anyway code such can define or condition in middleware?
for role based authentication i'm using middleware:
namespace app\http\middleware; use auth; use closure; use app\role; use illuminate\support\collection; class rolemiddleware { /** * handle incoming request. * * @param \illuminate\http\request $request * @param \closure $next * @return mixed */ public function handle($request, closure $next, $roles = null, $guard = null) { $roles = role::wherein('slug', explode('|', $roles))->get(); if (! auth::guard($guard)->user()->hasrole($roles)) { return abort(403, 'forbidden'); } return $next($request); } }
then register middleware in kernel.php
'role' => \app\http\middleware\rolemiddleware::class,
on user model make sure have method check if user has set of roles, example:
public function hasrole($role) { if (is_int($role)) { return $this->roles->contains('id', $role); } if (is_string($role)) { return $this->roles->contains('slug', $role); } if ($role instanceof model) { return $this->roles->contains('id', $role->id); } return !! $role->intersect($this->roles)->count(); }
and can use middleware this:
route::group(['middleware' => ['auth', 'role:admin|staff'], ...);
you can replace admin|staff
role names, separated |
. if want add custom guard
can pass second parameter role:admin|staff,mycustomguard
Comments
Post a Comment