Search code examples
phplaraveleloquentlaravel-query-builder

Creating and Update Laravel Eloquent


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
}

Solution

  • 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