Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel attempt to read property on null

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

The optional helper is intended for this purpose.

optional($user->permissions)->is_admin
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading