Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a new record if not exist and don't update if exist, laravel eloquent

Tags:

laravel

Should I use create method to insert a new record if doesn't exist and don't update the record if exist? Thanks.

like image 736
Adrian Cobb Avatar asked Nov 26 '15 03:11

Adrian Cobb


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.
}
like image 92
Joseph Silber Avatar answered Nov 09 '22 21:11

Joseph Silber


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;
}
like image 42
Carlos Torres Avatar answered Nov 09 '22 21:11

Carlos Torres