Search code examples
laraveleloquentlaravel-7

Laravel how to return virtual generated column on model create


I have the following table:

| id | number_one | number_two | number |
| 1  | 10         | 20         | 10020  |

Where number is a virtual created combination of number_one and number_two. Now when accessing a row the Laravel model also does return the number as expected.

Number::find(1); // returns [ id => 1, number_one => 10, number_two => 20, number => 10020]

However when using

Number::create(['number_one' => 10, 'number_two' => 21]);

It only returns

[number_one => 10, number_two => 21, id => 2]

So my question is how can I make it return the following on create:

[ number_one => 10, number_two => 21, number => 10021, id => 2]

And yes I could use a additional query or a getNumberAttribute method but would like to avoid this


Solution

  • Since create is causing an INSERT statement, there isn't a SELECT happening to get the fields from the table. You will notice that if you have a table that has default values and you don't pass those fields you also won't have them in your model.

    To get these fields you would need to do a SELECT. You can call refresh on the Model instance to have its attributes and relationships refreshed from the database or you can also call fresh to get a new instance from the database (basically a find). [both methods will return a Model instance]

    $model = Model::create([...])->refresh();
    // or
    $model = Model::create([...])->fresh();