32

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 2

72

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.
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
2

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

The updateOrCreate method is now in the docs: laravel.com/docs/5.5/eloquent#other-creation-methods
The question was about not updating record if exists
This answers a different problem, not what OP asked..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.