Laravel 8 - firstOrCreate() doesn't return Default value set in the DB

Viewed 894

My MySQL DB has a default value set to 0 for field formed_id:

`former_id` bigint(20) NOT NULL DEFAULT 0 

When I use firstOrCreate() method to insert a new record, I do not set formed_id:

$record = Record::firstOrCreate(
   [
      "name" => "myName",
      "nick"  => "myNick",
   ]
);

and the output returns:

{
   "id": 10,
   "name" => "myName",
   "nick  => "myNick",
   "created_at" => "2020-10-01 00:00:00",
   "updated_at" => "2020-10-01 00:00:00",
}

do not contains the former_id field set as default, 0.


To get all fileds in the output model, I need to perform a second query:

$record = Record::firstOrCreate(
   [
      "name" => "myName",
      "nick  => "myNick",
   ]
);
$fullRecord = Record::find($record->id)

in this case the output returns correctly:

{
   "id": 10,
   "name" => "myName",
   "nick  => "myNick",
   "former_id" => 0,
   "created_at" => "2020-10-01 00:00:00",
   "updated_at" => "2020-10-01 00:00:00",
}

I do not like this solution because I need to perform two queries instead of one; is there a way to get all fields directly from the firstOrCreate() insert?

Thank you.

2 Answers

This is indeed correct behaviour. It could be highly inefficient by default to fetch a model directly after it has been created.

In your case you could add an $attributes property to your model to achieve default properties and prevent having to do another query.

/**
 * The model's attributes.
 *
 * @var array
 */
protected $attributes = [
    'former_id' => 0,
];
Related