Problem
What’s the best and quickest way to create a new record using Laravel Eloquent or update the record if it exists ?
<?php
$user = User::where('organization_id', '=', $organization_id)
->where('age', '=', 30)->first();
if ($user == null) {
// Insert a new record into the database
} else {
// Update the existing record
}
$user = User::where('organization_id', '=', $organization_id)
->where('age', '=', 30)->first();
if ($user == null) {
// Insert a new record into the database
} else {
// Update the existing record
}
Solution
Including Laravel 6, there has been a couple of ways to create and update your Eloquent record separately. What you need here is one method that does all of this for you. You could use firstOrNew or firstOrCreate. The difference is that the first one only return an instance of the model, meaning that you have the object, but it hasn’t been persisted into the database yet. You would have to call save() method on it. The other one will do all of this for you.
$user = User::firstOrNew(['name' => 'Laravel Recipes']);
$user->age = Input::get('age');
$user->save();
$user->age = Input::get('age');
$user->save();
Below is the updated link of the docs which is on the latest version of Laravel
Docs here: Updated link