I'm using simple Gates
user permissions on my Laravel
.
I have a permissions table with hasOne relationship:
class User extends Authenticatable
{
public function permissions()
{
return $this->hasOne(UserPermission::class);
}
}
and in an AuthServiceProvider
I have to register permission:
public function boot()
{
$this->registerPolicies();
Gate::define('is_admin', fn(User $user) => $user->permissions->is_admin);
Gate::define('is_test_user', fn(User $user) => $user->permissions->is_test_user);
//
}
but when the record doesn't exist in my permission table then I have an error: Attempt to read property "is_admin" on null
.
What's the best solution for this problem?
CodePudding user response:
The optional
helper is intended for this purpose.
optional($user->permissions)->is_admin