Creating and Update Laravel Eloquent

1myb picture 1myb · Sep 17, 2013 · Viewed 330k times · Source

What's the shorthand for inserting a new record or updating if it exists?

<?php

$shopOwner = ShopMeta::where('shopId', '=', $theID)
    ->where('metadataKey', '=', 2001)->first();

if ($shopOwner == null) {
    // Insert new record into database
} else {
    // Update the existing record
}

Answer

weotch picture weotch · Jan 9, 2014

Here's a full example of what "lu cip" was talking about:

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save();

Below is the updated link of the docs which is on the latest version of Laravel

Docs here: Updated link