Skip to content
Advertisement

Attempt to read property “permissions” on null in Laravel 8

I am trying to register a user to the system and assign the patient role by default. The problem arises in the RegisterController controller. In the create () method I write the following code:

protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        $role = AppModelsRole::where('slug', 'paciente')->first();
        $permissions = $role->permissions;

        $user->roles()->attach($role);
        $user->permissions()->sync($permissions);

        return $user;
    }

The error that laravel 8 throws is the following: Attempt to read property “permissions” on null

It is not recognizing as such the related permissions of the role saved in the $ permissions variable. What is the solution?

From already thank you very much!!!

Advertisement

Answer

As I said in comments, it seems that you don’t have the ‘role’ in your DB with field ‘slug’ = ‘paciente’. That’s why in this line

$role = AppModelsRole::where('slug', 'paciente')->first(); 

$role is null. Check your role’s table

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement