-
Hi! I am trying to use the hasRole in the booted method of a model but it is not working as expected. It is checking against all the roles in the database, not just against the roles of the current auth user. protected static function booted()
{
if (auth()->check() && auth()->user()->hasRole('manager')) {
static::addGlobalScope(...);
}
} This is happening if I use other methods. For example, using select
"roles".*,
"model_has_roles"."model_id" as "pivot_model_id",
"model_has_roles"."role_id" as "pivot_role_id",
"model_has_roles"."model_type" as "pivot_model_type"
from
"roles"
inner join "model_has_roles" on "roles"."id" = "model_has_roles"."role_id" For some reason, it is failing to add the where clause: where
"model_has_roles"."model_id" = 2
and "model_has_roles"."model_type" = 'App\Models\User'
Does anybody knows what is happening or how to fix this? I am guessing this has something to do with the way laravel executes, but not sure. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
package version ? laravel version?
I suspect the same |
Beta Was this translation helpful? Give feedback.
-
Hi @erikn69, thanks for your answer. I have doing some debugging and research and it seems that Laravel relationships are not available during the |
Beta Was this translation helpful? Give feedback.
Hi @erikn69, thanks for your answer.
I have doing some debugging and research and it seems that Laravel relationships are not available during the
booted
method, so that's why thehasRole('manager')
fails to append the where clause. I am not 100 percent sure this is what is happening, but seems to be the case. For now, my solution was to do the query myself, not using the Laravel relations.