Should I use create method to insert a new record if doesn't exist and don't update the record if exist? Thanks.
2 Answers
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.
}
2 Comments
Muhammad Usama Mashkoor
how we can find out if a record is created and how we can find out if record is not created because it was already existing.
Joseph Silber
@usama - you can check the model's
wasRecentlyCreated property, which tells you whether the model was just created. If it was fetched from the database, $user->wasRecentlyCreated will be false.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;
}
3 Comments
Tobias Beuving
The updateOrCreate method is now in the docs: laravel.com/docs/5.5/eloquent#other-creation-methods
Vyshnia
The question was about not updating record if exists
DJ Far
This answers a different problem, not what OP asked..