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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -