Laravel Model Create method returns incomplete fields model instance

Viewed 1532

I am having an issue retrieving my model data after insertion. Below is a sample code in which User model has already its $fillable containing all needed attributes (id and state attributes as extras to the below ones).

$values = ['firstname' => 'Nick', 'lastname' => 'King', 'gender' => 'male' ];
$createdUser = User::create( $values );

Here is the migration code :

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('firstname', 60);
        $table->string('lastname', 60);
        $table->string('gender', 6);
        $table->string('state', 20)->default('inactive');
        $table->timestamps();
    });

When sending back the $createdUser as JSON, I noticed that the state attribute doesn't exists. It does exists in the migration having a default value and also in the model $fillable but not in the $hidden attribute. So what's wrong?

Is that a bug for not having fields inserted with their default values in the returned model or it's just the way Laravel works.

2 Answers

Another way to give default values on your Models is to add an $attributes property to your Model classes:

protected $attributes = ['state' => 'inactive'];

This should set the default values on the Model instance when you create a new model without having to hit the database again after you create it to get the defaults.

The enum field should have predefined values:

$table->enum(‘state’, [‘active’, ‘inactive’])->default(‘inactive’);

I would also store gender the same way.

Related