Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ollie_123's avatar

updateOrCreate - Ajax only trying to create

Hi All

I'm trying to update a record using Ajax and being new to Ajax & laravel i'm confused about the result of the query. I'm trying to update a record but when i make the Ajax call, its trying to insert a new record into the DB.

Please could someone point me in the right direction as to where i'm going wrong?

Error:

SQLSTATE[HY000]: General error: 1364 Field 'lname' doesn't have a default value (SQL: insert into `users` (`id`, `fname`, `email`, 

Controller:

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {  
        $dealerApp = \App\User::updateOrCreate(
            ['id' => $request->dealerApp_id],
            ['fname' => $request->fname, 'email' => $request->email]
        );
        return Response::json($dealerApp);
    }
    
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\User  $User
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $where = array('id' => $id);
        $dealerApp  = \App\User::where($where)->first();
 
        return Response::json($dealerApp);
    }

Script in view file:

$(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    /*  When user click add user button */
    // $('#create-new-user').click(function () {
    //     $('#btn-save').val("create-user");
    //     $('#userForm').trigger("reset");
    //     $('#userCrudModal').html("Add New User");
    //     $('#ajax-crud-modal').modal('show');
    // });
 
   /* When click edit user */
    $('body').on('click', '#edit-user', function () {
      var dealerApp_id = $(this).data('id');
      $.get('dealerApp/' + dealerApp_id +'/edit', function (data) {
         $('#userCrudModal').html("Edit User");
          $('#btn-save').val("edit-user");
          $('#ajax-crud-modal').modal('show');
          $('#user_id').val(data.id);
          $('#fname').val(data.fname);
          $('#email').val(data.email);
      })
   });
   //delete user
    $('body').on('click', '.delete-user', function () 
    {
        var dealerApp_id = $(this).data("id");
        if(confirm("Are You sure want to delete !")) 
        {
 
            $.ajax
            ({
                type: "DELETE",
                url: "{{ url('dealerApp/update')}}"+'/'+dealerApp_id,
                success: function (data) 
                {
                    $("#dealerApp_id" + dealerApp_id).remove();
                },
                error: function (data) 
                {
                    console.log('Error:', data);
                }
            });
        }
    });   
  });
 
 if ($("#userForm").length > 0) {
      $("#userForm").validate({
 
     submitHandler: function(form) {
 
      var actionType = $('#btn-save').val();
      $('#btn-save').html('Sending..');
      
      $.ajax({
          data: $('#userForm').serialize(),
          url: "{{ url('dealerApp') }}",
          type: "POST",
          dataType: 'json',
          success: function (data) {
            console.log('Success:', data); // will remove this for production & add PNotify
               
              
            //   if (actionType == "create-user") {
            //       $('#users-crud').prepend(dealerApp);
            //   } else {
            //       $("#user_id_" + data.id).replaceWith(user);
            //   }
 
              $('#userForm').trigger("reset");
              $('#ajax-crud-modal').modal('hide');
              $('#btn-save').html('Save Changes');
              
          },
          error: function (data) {
              console.log('Error:', data); //  will remove this for production
              $('#btn-save').html('Save Changes');
          }
      });
    }
  })
}

Ultimately i will change the field to update the status of the user but for now i just need to get it functioning.

Thank you in advance.

0 likes
9 replies
Nakov's avatar
Nakov
Best Answer
Level 73

@oli_d111

But this means that a User with the dealerApp_id does not exists yet, that's why it tries to insert, but you are missing some fields, like the lname which does not have a default value and it is not nullable.

Make sure that this $request->dealerApp_id has a value as well, and that the user really exists.

ollie_123's avatar

Ah amazing, thanks @nakov. This now update & submits to the DB, however the table doesn't update unless i refresh the page.

In regards to the table, please can you suggest the best way to refresh the table after an update?

I did put an ID on the body of the table and tried to get it to reset but it doesn't seem to work.

The body id was #updateTable and i tried to use

$('#updateTable').trigger("reset");

but no joy, for reference, its a bootstrap table not Datatables etc.

Thanks in advance.

Nakov's avatar

Unless you are manually updating the cells in your table, then there is no way that using AJAX you can refresh it unless you reload the page. So in this cases, I do refresh the page in the success callback using:

window.location.href = window.location.href;

// or

window.location.reload();
ollie_123's avatar

Awesome thank you. Shame, i thought it would have been possible. Great suggestion on the window.location.reload(). Thanks for your help much appreciated. :)

ollie_123's avatar

Sorry to be that guy, but why would it only allow me to update only the fname and none of the other fields?

/* When click edit user */
    $('body').on('click', '#edit-user', function () {
      var dealerApp_id = $(this).data('id');
      $.get('dealerApp/' + dealerApp_id +'/edit', function (data) {
         $('#userCrudModal').html("Edit User");
          $('#btn-save').val("edit-user");
          $('#ajax-crud-modal').modal('show');
          $('#user_id').val(data.id);
          $('#fname').val(data.fname);
          $('#lname').val(data.lname);
          $('#email').val(data.email);
          $('#status').val(data.status);
      })
   });

This outputs data from the table into the modal but if i amend any of the fields except for the fname it doesn't update. I've tried outputting to the console and checking the error logs but its not giving me a reason as to why.

public function store(Request $request)
    {  
        $dealerApp = \App\User::updateOrCreate(
            ['id' => $request->user_id],
            [
                'fname' => $request->fname, 
                'email' => $request->email,
                'status' => $request->status,

            ]
        );
        return Response::json($dealerApp);
    }
    
    
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\User  $User
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {   
        $where = array('id' => $id);
        $dealerApp  = \App\User::where($where)->first();
 
        return Response::json($dealerApp);
    }

Please can you advise.

Thanks in advance.

Nakov's avatar

@oli_d111 but in your controller, you are not even adding the lname for example:

 [
   'fname' => $request->fname, 
   'email' => $request->email,
   'status' => $request->status,
]

The first array in the updateOrCreate is to find a matching row, and the second is to fields used to update or create. Am I misunderstanding your question?

ollie_123's avatar

That's a fair point however the main one i'm trying to update is status. In the modal i've got a dropdown but it won't take the values from the dropdown and update the DB?

<div class="row">
  <div class="col-sm-12">
     <label>Status</label>
     <select type="text" class="form-control" id="status" name="status">
         <option hidden>Select</option>
         <option value="Approved">Approved</option>
         <option value="Rejected">Rejected</option>
     </select>
  </div><!-- end col -->
</div><!-- end row -->
Nakov's avatar

@oli_d111 well for this one you need to check if your data contains the Status. I usually debug JavaScript code using console.log and checking the Console tab in the browser.

So add console.log(data); and make sure that data.status contains the correct value. Or explore the Network tab for the request that you make, and make sure that the new value is there.

Also in your User model, make sure that you have status in the $fillable array.

ollie_123's avatar

Thanks @nakov appreciate your help. Feel like a complete tool now as it was missing from the User Model. Not sure why i didn't check there... DOH!.

Thanks again :)

Please or to participate in this conversation.