Gammer
Gammer

Reputation: 5628

laravel updateOrCreate method

I have the following code in my method which I am sending via ajax to the controller method :

    $newUser = \App\UserInfo::updateOrCreate([
        'user_id'   => Auth::user()->id,
        'about'     => $request->get('about'),
        'sec_email' => $request->get('sec_email'),
        'gender'    => $request->get("gender"),
        'country'   => $request->get('country'),
        'dob'       => $request->get('dob'),
        'address'   => $request->get('address'),
        'mobile'    => $request->get('cell_no')
    ]);

The dd($request->all()) gives me :

array:8 [
  "_token" => "fHeEPfTvgMD3FpIBmmc6DmKXFaiuWKZEiOhg6twQ"
  "about" => "Some about me."
  "sec_email" => "[email protected]"
  "country" => "Priority highest"
  "gender" => "male"
  "dob" => "12/12/1990"
  "address" => "Some address"
  "cell_no" => "234234234"
]

which is perfect.

Jquery code :

$('#submit-editProfile-form').on('click', function() {
    var profileEditForm = $("#edit-user-profile");
    var formData = $('#edit-user-profile').serialize();
    profileEditForm.on('submit', function(e){
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url:'/freelance/edit-userProfile-info',
            type:'POST',
            data:formData,
            error: function (data) {
               console.log('Error');
            }
        });
    }).submit();
});

Now the problem is that i have a record in my table, But the above code creates another one, And the second is that it creates multiply by two records on each button click (request).

Upvotes: 77

Views: 325712

Answers (5)

bart2puck
bart2puck

Reputation: 2522

to add to what @mahmoud said.

                $insDB = IP::updateOrCreate(
                    ['field1' => $value1,
                    'field2' => $value2,
                    'field3' => $value3,
                    ],
                    [
                     'field4' => $value4,
         'field5' => $value5,
                     ]
                );

adding

    protected $primaryKey = 'field1';

will allow multiple columns to be compared as unique and also get rid of the "no column id found" error

Upvotes: 0

Mahmoud abouelawad
Mahmoud abouelawad

Reputation: 1

One more thing, if you try to use a primary key other than the default which is (id), You probably face an error that says "Column not found: 1054 Unknown column 'id' in 'where clause'", and you will find also in the error where id is null...

All you need is to set the default primary key in the user model let's assume it is App\Models\Post

then write protected $primaryKey = 'user_id'

that's it :)

Upvotes: 0

Mohit Nandpal
Mohit Nandpal

Reputation: 143

In Laravel, the createOrUpdate() method is used to determine whether or not data exists and then create a new entry or update an existing entry in the table.

Note: You should include a condition in the method in your case. otherwise, it will create a new entry.

For example, if you wish to check the user_id, the code is as follows:

$newUser = \App\UserInfo::updateOrCreate([
    //Add your condition here.
    //For ex: you want to add or update data by user_id:
    'user_id'   => Auth::user()->id,
],[
    'about'     => $request->get('about'),
    'sec_email' => $request->get('sec_email'),
    'gender'    => $request->get("gender"),
    'country'   => $request->get('country'),
    'dob'       => $request->get('dob'),
    'address'   => $request->get('address'),
    'mobile'    => $request->get('cell_no')
]);

Using these two parameters, the method will check to see if the specified authorized user_id exists and then update the data; else, it will create new data.

Checkout official documentation: https://laravel-news.com/firstornew-firstorcreate-firstor-updateorcreate

Upvotes: 2

Rhu
Rhu

Reputation: 2179

In your use case, you should specify a second parameter. The first indicates the conditions for a match and second is used to specify which fields to update.

$newUser = \App\UserInfo::updateOrCreate([
    //Add unique field combo to match here
    //For example, perhaps you only want one entry per user:
    'user_id'   => Auth::user()->id,
],[
    'about'     => $request->get('about'),
    'sec_email' => $request->get('sec_email'),
    'gender'    => $request->get("gender"),
    'country'   => $request->get('country'),
    'dob'       => $request->get('dob'),
    'address'   => $request->get('address'),
    'mobile'    => $request->get('cell_no')
]);

Here is an example from the documentation: https://laravel.com/docs/5.4/eloquent#other-creation-methods

// 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]
);

Upvotes: 174

Oscar Gallardo
Oscar Gallardo

Reputation: 2728

Eloquent has the method called updateOrCreate, which can be used like this example:

<?
$flight = UserInfo::updateOrCreate(
    [
       'user_id'   => Auth::user()->id,
    ],
    [
       'about'     => $request->get('about'),
       'sec_email' => $request->get('sec_email'),
       'gender'    => $request->get("gender"),
       'country'   => $request->get('country'),
       'dob'       => $request->get('dob'),
       'address'   => $request->get('address'),
       'mobile'    => $request->get('cell_no')
    ],
);
  1. Search by user_id could be your best way to identify your rows.
  2. It creates or updates according to the values given in the second array.

The following is the sign of the method.

/**
 * Create or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model
 */
public function updateOrCreate(array $attributes, array $values = [])

Upvotes: 12

Related Questions