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

salmankhan2482's avatar

assign role and permission to a user dynamically laravel 7

i created the system where permission are created dynamically and as well as roles. then the permissions are assigned to roles and roles are then assigned to users.

and when i run the below code in edit function of propertiescontroller

if (Gate::allows('property_edit')) {
            dd('yes');        
        }else{
            dd('no');        
        }

and hence i created the permission named as 'property_edit' and assign the permission to role 'Admin' and assign this role to admin user still i m getting no

0 likes
8 replies
salmankhan2482's avatar

@siangboon i have almost 100+ permissions, so how can i check each user against the specific permission that whether that user is allowed or not ?

so should i have to define that much gates or can pass the permission dynamically to check against the logged in user ?

Snapey's avatar

typically you would register the gate inside a loop

foreach (Permission::all() as $permission) {
    Gate::define($permission->name, function (User $user, $thing) use ($permission){

       $action= $permission->name;

        // do your check, can $user do $action with $thing

    });
}

so then you need to check if the passed user has the explicit permission, or a role that grants that permission

1 like
salmankhan2482's avatar

@Snapey the code in controller

if($permission = Permissions::where('title', 'property_create')->first()){
            if (!Gate::allows('isAllowedToThis', $permission->id)) {
                \Session::flash('flash_message', "You Are Not Authorized.");
                return redirect()->back();
            }
        }

the code in AuthServiceprovide

Gate::define('isAllowedToThis', function($user, $permission = '') {
            foreach ($user->roles as $key => $value) {
                return $value->rolepermissions->contains($permission);
            }
        });
salmankhan2482's avatar

it works fine dear sir, but still i need to confirm is it an appropriate way of doing it ?

salmankhan2482's avatar

@Snapey sir there is a many to many relationship between roles and permission and users and roles. and you mentioned thing in the above query. what does thing means right there in above query ?

Please or to participate in this conversation.