Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

How to create middleware based on multiple conditions

Hi, I have a tables like below,

roles

id, name

role_permissions

id,role_id,can_access_admin,can_access_journal

in users table,

id, default_role_id,name,email

role_users

id, role_id,user_id,

User.php

 public function role()
    {

        return $this->belongsTo('App\Models\Role', 'role_id', 'id');
    }

/**
     * A user belongs to many user roles (e.g. admin.manager)
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany('App\Models\Role')->withTimestamps();
    }

public function authorizeRoles($roles)
    {
      if ($this->hasAnyRole($roles)) {
        return true;
      }
      abort(401, 'This action is unauthorized.');
    }

    public function hasAnyRole($roles)
    {
      if (is_array($roles)) {
        foreach ($roles as $role) {
          if ($this->hasRole($role)) {
            return true;
          }
        }
      } else {
        if ($this->hasRole($roles)) {
          return true;
        }
      }
      return false;
    }

public function hasRole($role)
    {
      if ($this->roles()->where('name', $role)->first()) {
        return true;
      }
      return false;
    }

public function hasAnyRolePermission($roles,$action_name)
    {
        if (is_array($roles)) {
            foreach ($roles as $role) {
                $userrole = $this->roles()->where('name', $role)->first();
                if($userrole) {
                    if ($userrole->permission->$action_name)
                        return true;
                    return false;
                }
            }
          } else {
            $userrole = $this->roles()->where('name', $role)->first();
            if($userrole) {
                if ($userrole->permission->$action_name)
                    return true;
                return false;
            }
          }
        return false;
    }


Role.php

public function permission()
    {
        return $this->hasOne('App\Models\RolePermission');
    }

RolePermission.php

public function role()
    {
        return $this->belongsTo('App\Models\Role', 'role_id', 'id');
    }

i have a middleware like below,

public function handle(Request $request, Closure $next, ...$role)
    {   
        if (! $request->user()->authorizeRoles($role)) {
            abort(401, 'This action is unauthorized.');
        }
        return $next($request);
    }

and also i have permissions for certain modules and fetching user has access to that model or not using below code,

if(!auth()->user()->hasAnyRolePermission(['Admin','JournalAdmin'],'can_create_journal'))
        return noPermission(url('admin/dashboard'));

right now i am adding this code in all controller functions. is there any way i can add this to middleware and pass the permission to that middleware (ex can_create_journal,can_view_journal) instead of calling this code in all controller function?

0 likes
2 replies
koramit's avatar

@deekshith

Maybe you fixed it by now but if it not the case, you can user Gate and Policy

https://laravel.com/docs/8.x/authorization

https://laracasts.com/series/laravel-6-from-scratch/episodes/50

so you can register condition at AuthServiceProvider like this

    public function boot()
    {
        Gate::before(function ($user, $ability) {
            if ($user->abilities->contains($ability)) { // user has many abilities
                return true;
            }
        });
    }

then you can use gate as a middleware like this

// user can create note if they have 'create_note' abilities
Route::post('notes', 'Notes\NotesController@store')
          ->middleware('auth', 'can:create_note');

Please or to participate in this conversation.