69

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" => "example@gmail.com"
  "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).

Amir
  • 8,821
  • 7
  • 44
  • 48
Gammer
  • 5,453
  • 20
  • 78
  • 121

3 Answers3

161

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]
);
dustbuster
  • 79,958
  • 7
  • 21
  • 41
Rhu
  • 2,049
  • 1
  • 11
  • 11
  • 7
    Stop me if I'm wrong, but looking at how this method works, I don't believe the `'user_id' => Auth::user()->id,` is necessary on the second parameter. Builder::updatedOrCreate() sends the first parameter to firstOrNew(), meaning your user Id will be applied to the new entry anyway, if one is to be created. – kmuenkel Sep 18 '17 at 20:52
  • 1
    Nice catch @Claymore! I've updated my code snippet. It would work fine either way but it's definitely nicer this way. – Rhu Dec 04 '17 at 16:01
  • How do you select what table in the database it should check on? – TheCrazyProfessor Dec 28 '17 at 16:07
  • This solved it for me. Our code had Fylke::updateOrCreate($county); Where $county was an array where the first element was the key. I changed the code to $key = array_slice($county, 0, 1); Fylke::updateOrCreate($key, $county); Problem solved. Thanks. – Erlend Oct 27 '21 at 14:58
  • 1
    Never gets old, i always come here if i had confusion. :D – Vipertecpro Aug 18 '22 at 07:56
  • I want to update the same parameter that I'm matchingm Whay can I do? – Wakil Ahmed Sep 15 '22 at 14:13
  • How do you add a search column that may or may not have a value? I mean, a field that can either have a value or be null. I can't find a way to implement it in that array like explained in [this answer](https://stackoverflow.com/a/36372109/1883256) – Pathros Oct 06 '22 at 21:31
  • How do you update a `belongsTo` relationship column? – Pathros Oct 06 '22 at 21:36
10

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 = [])
Oscar Gallardo
  • 2,240
  • 3
  • 27
  • 47
  • How do you add a search column that may or may not have a value? I mean, a field that can either have a value or be null. I can't find a way to implement it in that array like explained in [this answer](https://stackoverflow.com/a/36372109/1883256) – Pathros Oct 06 '22 at 21:30
  • How do you update a `belongsTo` relationship column? – Pathros Oct 06 '22 at 21:36
0

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