Best Way to Insert or Update Records in Laravel Eloquent?

I’m trying to find out What’s the shortest way to insert a new record or update it if it exists in Laravel Eloquent. Currently, I’m using the following approach to check if a record exists based on a specific key and then either insert a new record or update the existing one:

if (!Setting::where('key', $settingKey)->exists()) {
    // Insert new record into database
} else {
    // Update the existing record
}

Is there a shorter and better option available in Laravel for achieving the same functionality?

You can try updateOrCreate or firstOrNew method which will allow you to achieve this more shortly and cleanly.

Setting::updateOrCreate(
    ['key' => $settingKey],
    ['value' => $settingValue] 
);

OR

$setting = Setting::firstOrNew(['key' => $settingKey]);
$setting->value = $settingValue;
$setting->save();

If you have multiple columns you can use fill method.

$setting->fill($settingValue)->save();