Skip to content
Advertisement

Laravel Models properties declaration

I have the following model:

class User extends Authenticatable
{
 private string $first_name;

 public function name()
 {
  return $this->first_name;
 }
}

when I call that method from a controller, I’m getting

User::$first_name must not be accessed before initialization

Also, if I’m commenting/removing the declaration of property, the method runs well with no errors.

Advertisement

Answer

PHP 7.4 introduced typed properties. Typed properties need to be initialised before accessing it. You can read more about that error in this article

That’s why typed properties without a default value now have an uninitialized state. When calling a method that accesses such an uninitialized state, you’ll get the “Typed property User::$username must not be accessed before initialization” error.

Note that nullable typed properties also have this uninitialized state instead of having null as default value.

So simply initialising it will fix the error: private string $first_name = "init value";

But since you reference Models in the question title I assume you are using Eloquent models.

class User extends Authenticatable {
    ...
}

And then you also don’t need to put the model properties on the class. Eloquent will automatically map the database fields as properties on the object.

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