Home > Net >  How to bind model to the Spatie role?
How to bind model to the Spatie role?

Time:01-02

Is it possibe to attach specific model to the role in Spatie laravel permissions?

I need to get model depends role. For example if user has role doctor I need to get Doctor model. The same for clinic role.

CodePudding user response:

Its a little hard to know what you are hunting for without knowing how you've set up the architecture underneath this, but you can get to the Doctors... not sure about binding directly though.

I assume you have created a Spatie role and assigned it to a Doctor class (which I assume is an extended User or similar, and is using HasRoles):

$role = Role::create(['name' => 'doctor']);

Grab a doctor and assign the role as normal:

$doctor = Doctor::find(xxx);
$doctor->assignRole($role);

I think the below may help:

$role= Role::findByName('doctor');
$roleClass= $role->getModel();

For the Docs with role doctor

$docs= Doctor::role('doctor')->get();

If you are looking to distinguish between class (Doctor, User), you'll need to run an extra command on a$doc (or even a superset like User::role collection) like get_class but this will depend on how you've set the query and flow up. I'm not sure there is a direct method in Spatie to do exactly how you wish, but if you are OK with pulling a superset collection of users which might include the Doctor class, you can do it in two steps at least.

  • Related