-
Hi! class User extends Authenticatable
{
use HasRoles;
public function isAdmin(): Attribute
{
return Attribute::make(
get: fn () => $this->hasRole('admin'),
);
}
} Using this accessor anywhere in your app will cause the roles relationship to be added to the array/json representation of your User model which is not normally desired, especially when you pass the model to a frontend like inertia and you are not filtering your Vue props. This is caused because the public function hasRole($roles, string $guard = null): bool
{
$this->loadMissing('roles'); // loading the roles relationship
return $this->roles->contains('name', $roles); // using the loaded roles collection
return (bool) $this->roles()->whereIn('name', $roles)->count(); // using query builder
} Why not use the query builder instead of the collection to avoid adding roles to user model representation? Thank you very much! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
For avoid calling db on every |
Beta Was this translation helpful? Give feedback.
For avoid calling db on every
hasRole