Creating and Update Laravel Eloquent

laravel model example
laravel update data
updateorcreate laravel
laravel update or create not working
laravel cursor
laravel query builder insert or update
laravel update or create multiple
laravel pivot model

What's the shorthand for inserting a new record or updating if it doesn't exist?

<?php

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

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

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

Eloquent ORM - Laravel, An online course for developers wanting to learn all the tools and workflow involved in using Laravel's Eloquent ORM. Problem What’s the best and quickest way to create a new record using Laravel Eloquent or update the record if it exists ? 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 …

Updated: Aug 27 2014 - [updateOrCreate Built into core...]

Just in case people are still coming across this... I found out a few weeks after writing this, that this is in fact part of Laravel's Eloquent's core...

Digging into Eloquent’s equivalent method(s). You can see here:

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L553

on :570 and :553

    /**
     * Create or update a record matching the attributes, and fill it with values.
     *
     * @param  array  $attributes
     * @param  array  $values
     * @return static
     */
    public static function updateOrCreate(array $attributes, array $values = array())
    {
        $instance = static::firstOrNew($attributes);

        $instance->fill($values)->save();

        return $instance;
    }

Old Answer Below


I am wondering if there is any built in L4 functionality for doing this in some way such as:

$row = DB::table('table')->where('id', '=', $id)->first();
// Fancy field => data assignments here
$row->save();

I did create this method a few weeks back...

// Within a Model extends Eloquent
public static function createOrUpdate($formatted_array) {
    $row = Model::find($formatted_array['id']);
    if ($row === null) {
        Model::create($formatted_array);
        Session::flash('footer_message', "CREATED");
    } else {
        $row->update($formatted_array);
        Session::flash('footer_message', "EXISITING");
    }
    $affected_row = Model::find($formatted_array['id']);
    return $affected_row;
}

I Hope that helps. I would love to see an alternative to this if anyone has one to share. @erikthedev_

Creating and Update Laravel Eloquent, 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  Eloquent models fire several events, allowing you to hook into the following points in a model's lifecycle: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. Events allow you to easily execute code each time a specific model class is saved or updated in the database.

As in Laravel >= 5.3, if someone is still curious how to do so in easy way. Its possible by using : updateOrCreate().

For example for asked question you can use something like:

$matchThese = ['shopId'=>$theID,'metadataKey'=>2001];
ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Above code will check the table represented by ShopMeta, which will be most likely shop_metas unless not defined otherwise in model itself

and it will try to find entry with

column shopId = $theID

and

column metadateKey = 2001

and if it finds then it will update column shopOwner of found row to New One.

If it finds more than one matching rows then it will update the very first row that means which has lowest primary id.

If not found at all then it will insert a new row with :

shopId = $theID,metadateKey = 2001 and shopOwner = New One

Notice Check your model for $fillable and make sue that you have every column name defined there which you want to insert or update and rest columns have either default value or its id column auto incremented one.

Otherwise it will throw error when executing above example:

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'

As there would be some field which will need value while inserting new row and it will not be possible as either its not defined in $fillable or it doesnt have default value.

For more reference please see Laravel Documentation at : https://laravel.com/docs/5.3/eloquent

One example from there is:

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

which pretty much clears everything.

Query Builder Update

Someone has asked if it is possible using Query Builder in Laravel. Here is reference for Query Builder from Laravel docs.

Query Builder works exactly the same as Eloquent so anything which is true for Eloquent is true for Query Builder as well. So for this specific case, just use the same function with your query builder like so:

$matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
DB::table('shop_metas')::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Of course, don't forget to add DB facade:

use Illuminate\Support\Facades\DB;

OR

use DB;

I hope it helps

Lesson 7: Creating and Updating, https://laravel.com/docs/5.3/eloquent#insert-update-delete Table2 model $​table2 = Table2::create($arrayOfData); // if the fields are fillables. If you’ve been working with Laravel for any time, you probably know the standard methods for creating Eloquent Models like make(), create(), update, and save(). Laravel includes some other methods are that also really useful for creating and updating Models that I feel don’t get enough attention.

Save function:

$shopOwner->save()

already do what you want...

Laravel code:

    // If the model already exists in the database we can just update our record
    // that is already in this database using the current IDs in this "where"
    // clause to only update this model. Otherwise, we'll just insert them.
    if ($this->exists)
    {
        $saved = $this->performUpdate($query);
    }

    // If the model is brand new, we'll insert it into our database and set the
    // ID attribute on the model to the value of the newly inserted row's ID
    // which is typically an auto-increment value managed by the database.
    else
    {
        $saved = $this->performInsert($query);
    }

Creating and Updating Laravel Eloquent, It performs create, retrieve, update, and delete (CRUD) operations, as well as maps object models to database tables. It handles all the database  Create and Update: The only actual difficulty here lies in the similarity of the functions that the QueryBuilder and Eloquent use. We've already seen that without Eloquent, to insert a new record into the database we use the DB facade.

firstOrNew will create record if not exist and updating a row if already exist. You can also use updateOrCreate here is the full example

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
); 

If there's a flight from Oakland to San Diego, set the price to $99. if not exist create new row

Reference Doc here: (https://laravel.com/docs/5.5/eloquent)

Inserting if record not exist, updating if exist, Hey guys, I am having trouble figuring out how to properly update or create a models related model. Here is an example of the problem I have. Create elegant slugs in Laravel models with ease. Generate elegant slugs when saving Laravel Eloquent Models. The package provides a trait that allows you to save a unique slugs to your database seamlessly by just specifying the seperator, source and destination field to generate a slug.

Laravel Eloquent Tutorial With Examples, In Laravel 5: There are two methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew. The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.

Eloquent relationship update or create, The Laravel Schema facade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems. Generating Migrations. To create a migration, use the make:migration Artisan command: php artisan make:migration create_users_table. The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations.

Bulk Insertion in Laravel using eloquent ORM. Ask Question @CanVural what should we do to update/create timestamps also? – Milan Maharjan Jul 21 '15 at 11:28. 3.

Comments
  • I'm guessing shopId is not your primary key, right?
  • @SergiuParaschiv, yep. it's not
  • Check out the answer from @ErikTheDeveloper. It shows a nice embeded eloquent method that should do the job.
  • The exact same thing is fully answered in the link below stackoverflow.com/questions/18839941/…
  • exactly! 'firstOrNew' also exists in 4.0 (not mentionned in the docs)
  • Also we can check $user is new/retrieved by using if($user->exists).
  • @Ryu_hayabusa That would likely cause race conditions
  • new syntax seems to be updateOrInsert(array $attributes, array $values = []) in 5.5: github.com/laravel/framework/blob/5.5/src/Illuminate/Database/…
  • There is and it's called firstOrNew / firstsOrCreate
  • @malcolmhall I've updated the answer above. It turns out Eloquent has many features that I've found myself rebuilding ;) Always good to spend some time browsing the docs :)
  • packagist's 4.2.0 (stable 2014/6/1) doesn't contain updateOrCreate. But one can implement it looking at the source. ModelName::firstOrNew(['param' => 'condition'])->fill(Input::get())->save(); should do it.
  • Just watch out that Laravel doesn't run it as a transaction, so if you have unique keys and another user creates it with the same key simultaneously you may get an exception. I believe that one of the advantages of RedBeanPHP is this type of thing is done in an a transaction for you.