Framework: Eloquent create, default enum property not being returned

Created on 12 May 2015  路  2Comments  路  Source: laravel/framework

When using Model::Create, it returns the model that was created with the id, created_at and updated_at fields. This would indicate that is returning the database version of the model, and not just the instance of model. However, I have a enum field which has a default value set in MySQL, and that value is not returned from the create method. I feel like this is unexpected behavior.

Say my model has an enum field called status, when the default value set to "In-Progress", given the below code:

$model = Model::create([
    'name'    => 'test',
    'user_id' => 2,
]);

dd($model);

returns

Model{
    'id' => 1,
    'name' => 'test',
    'user_id' => 2,
    "updated_at" => "2015-05-12 15:50:56",
    "created_at" => "2015-05-12 15:50:56",
}

It does not return the status field. In order to get the remaining properties I would have to do something like:

$model = Model::create($data);
$model = Model::find($model->id);
return $model;

I feel like it should return the entire model after create. This method also doesn't return relationships that are defined in the $with protected property either.

Is this unexpected behavior, or am I expecting too much from the create method?

Most helpful comment

Yes your expecting too much. Retrieving the record from the DB after creation means one extra DB query for every insert. Since in most cases the model is the correct representation of the data stored in the DB we don't need to run this extra query.

However what you can do to make your code look a bit nicer, use the fresh() method:

$model = Model::create($data)->fresh();

It will reload the model from the database (including relations specified in $with)

All 2 comments

Yes your expecting too much. Retrieving the record from the DB after creation means one extra DB query for every insert. Since in most cases the model is the correct representation of the data stored in the DB we don't need to run this extra query.

However what you can do to make your code look a bit nicer, use the fresh() method:

$model = Model::create($data)->fresh();

It will reload the model from the database (including relations specified in $with)

Alright, fair enough. Thanks for your response.

Was this page helpful?
0 / 5 - 0 ratings