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

radhamadhavamhostel's avatar

How to create middleware for my custom roles and permissions

I am trying to create a custom roles and permissions

roles Table

id | role_code |	name

User Table

id | username | email | user_type |

user_type in user table is the id from role table

Modules Table

id | module_code |	name

Permissions table

| id |	role_id |	module_id | permissions |
***  **********  ************** ***********
40469677-0331-4717-814b-7102f4b37d35 |	beb60b0e-bed4-4a77-9901-47113bbcba67 |	6ca38e62-6c50-438d-bdcd-0db8f563ac4c |	add,edit,view |

In controller

public function __construct()
    {
$this->middleware('auth');
       $this->middleware(function ($request, $next) {
       $role= Auth::user()->user_type;
       $module = Module::where('module_code', 'property_module')->first();
       $this->userModulePermissions = Permission::where('role_id', $role)
            ->where('module_id', $module->id)
            ->first();
        return $next($request);

  })
}
public function create()
    {
if ($this->userModulePermissions && in_array('add', explode(',', $this->userModulePermissions->permissions))) {
//relevent data
}else{
//no data
}

above code is working fine for me. So I used the same logic in a middleware called PermissionAndRoleCheck

PermissionAndRoleCheck

class PermissionAndRoleCheck
{
    protected $moduleCode;

    public function __construct($moduleCode = null)
    {
        $this->moduleCode = $moduleCode;
    }

    public function handle(Request $request, Closure $next)
    {
$role = Auth::user()->user_type;
        $module = Module::where('module_code', $moduleCode)->first();
        $userModulePermissions = Permission::where('role_id', $role )
            ->where('module_id', $module ->id)
            ->first();

        if (!$userModulePermissions) {
            return response()->json(['message' => 'No Data here.'], 403);
        }

        app()->instance('userModulePermissions', $userModulePermissions);

        return $next($request);
    }

And in my construct of controller

public function __construct()
    {
  $this->middleware(function ($request, $next) {
            $moduleCode = "property_module";
            $middleware = app()->make(PermissionAndRoleCheck::class, ['moduleCode' => $moduleCode]);
            $this->userModulePermissions = $request->attributes->get('userModulePermissions');
            return $next($request);
        });

}

Here $this->userModulePermissions alwayas NULL

0 likes
1 reply

Please or to participate in this conversation.