Livewire Error Fix: “Cannot assign null to property $name”

Resolving Null Value Assignment in Livewire Components

Troubleshooting “Cannot assign null to property $name”

What is actually the error?

Laravel 10 with the breeze and livewire project. When customizing the user profile area with adding extra fields like a unique username and about the field.

Cannot assign null to property Livewire\Volt\Component@anonymous::$name of type string

An error appears for the update-profile-information-form.blade.php file, in the mount function.

public function mount(): void
    {
        $this->name = Auth::user()->name;
        $this->email = Auth::user()->email;
    }

Above the name field is empty but we are using it. How do we make it nullable?

Solution

You just need to make the default value to show if there is a null field in the database.

public function mount(): void
    {
        $this->name = Auth::user()->name ?? '';
        $this->email = Auth::user()->email ?? '';
    }

Or make it more cleaner:

public function mount(): void
    { 
        $user = Auth::user();
        $this->name = $user->name ?? '';
        $this->email = $user->email ?? '';
    }

Related Posts