Insert a new entry if it does not exist and is not updated if it exists, laravel eloquent

Should I use the method createto insert a new record if it does not exist, and not update the record if it exists? Thanks.

+4
source share
2 answers

Use the method for this firstOrCreate:

$user = User::firstOrCreate(['name' => 'John Doe']);

If you want to know if the user was created or selected, check the property wasRecentlyCreated:

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.
}
+7
source

In Laravel 5.2, you have a method updateOrCreatefrom Builder.php, it uses the method firstOrNewto check if the specified attributes exist in db and update records with given values ​​or create and save new records.

, updateOrCreate :

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;
}
+1

Source: https://habr.com/ru/post/1617544/


All Articles