Should I use create
method to insert a new record if doesn't exist and don't update the record if exist? Thanks.
Use the firstOrCreate
method for that:
$user = User::firstOrCreate(['name' => 'John Doe']);
If you want to know whether the user was created or fetched, check the wasRecentlyCreated
property:
if ($user->wasRecentlyCreated) {
// "firstOrCreate" didn't find the user in the DB, so it created it.
} else {
// "firstOrCreate" found the user in the DB and fetched it.
}
In Laravel 5.2 you have the updateOrCreate
method from Builder.php, it uses the firstOrNew
method to verify if the given attributes exists in db and update the records with the given values or create and save the new records.
The weird thing is that updateOrCreate
doesn't appear in the docs:
https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function updateOrCreate(array $attributes, array $values = [])
{
$instance = $this->firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With