Laravel and x-editable team up to combat integrity constraint violation error code 1048, indicating no data being passed

Utilizing x-editable to generate an editable form that makes ajax requests. The form is structured as follows:

<a href="#" class="editable editable-click" id="mileage" 
        data-name="mileage" 
        data-type="number" 
        data-pk="{{ $car->id }}" 
        data-original-title="Enter mileage">
    {{ $car->mileage }}
</a>

Next, we have the JavaScript code:

$('#mileage').editable({
  url: '{{ route('changeMileage', $car->id) }}',
  type: 'number',
  pk: {{ $car->id }},
  name: 'mileage',
  title: 'Enter mileage in km',
  validate:function(value){
    if ($.trim(value) === '') {
      return "Field is required";
    }
  }
})

Within my controller:

$car = Car::where('id', $id)->first();

$this->validate($request, [
        'value' => 'number|min:' . $car->mileage . '|max:999999',
]);

$car->update([$car->mileage => $request->value]);

The controller logic may seem disorganized due to exploration of different versions. Validation is required (ensure entered mileage is not less than existing value).

However, upon sending the request, I encounter an

Integrity constraint violation: 1048
error related to an empty mileage field. Despite monitoring the intended request from the browser as
name=mileage&value=325000&pk=1
, dd($request->value) returns null.

The controller appears to be missing the value. Any suggestions for a solution?

P.S. Omission of checking for pk value, as the current page has only one editable field with necessary id information.

P.P.S. Attempted various methods, but even dd($request->all()) yields an empty array - [].

Answer №1

Despite x-editable being abandoned, I managed to make it work with the help of fellow developers.

I made a modification in my JavaScript code by adding the following line after all other options:

ajaxOptions: {
  dataType: 'json'
},

Prior to that, in the same JS file, I included a line to configure the ajax headers:

$.ajaxSetup({
  headers: {
    'Content-Type': 'application/json',
    "X-CSRF-Token": "{{ csrf_token() }}",
    'X-Requested-With': 'XMLHttpRequest',
    'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
});

In the Controller, I implemented a check to verify if the request is sent via ajax:

if($request->ajax()) {
  $car->update(['mileage' => $request->input('value')]);
  return response()->json(['success' => true]);
}

This results in the request being formatted as follows:

name=mileage&value=325002&pk=1

With these adjustments, everything functions smoothly!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue occurs when nested functions prevent the data() variable from updating

As a newcomer to VUE, I may not be using the right terminology so bear with me. I'm attempting to update a variable that is defined in the script tag's "data()" function. The issue arises when trying to change the value of a variable within the ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

Error encountered while attempting to load the vue-sanitize plugin within a Vue.JS application

Hi everyone, I'm encountering a problem with a plugin in Vue that I'm hoping to get some help with. Specifically, I am trying to incorporate vue-sanitize (available here: https://www.npmjs.com/package/vue-sanitize) into my project, but I keep re ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Attempting to execute JavaScript within HTML files that have been incorporated using Angular

My website has a menu designed in HTML, and instead of manually adding it to each page (which would make updating changes tedious), I am using Angular to include it dynamically (<div ng-include="menu.html"></div>). I've got some JavaScrip ...

Mapping custom colors to paths in D3 Sunburst visualizations can add a vibrant and unique touch

Currently, I am in the process of developing a D3 Sunburst Vue component and utilizing the npm package vue-d3-sunburst for this purpose. To access the documentation for the package, please visit: https://www.npmjs.com/package/vue-d3-sunburst The document ...

How can I find the last element that was selected using XPath in the browser console

Need help with XPath: $x(("//div[@class='ag-header-row']))[1] I'm working with an array of divs, but I want to select the last one. The [1] is necessary due to multiple rows with this class. I’ve heard about using [last()], but unsure w ...

Steps for iterating over the "users" list and retrieving the contents of each "name" element

I'm attempting to iterate over the "users" array and retrieve the value of each "name". Although the loop seems to be functioning correctly, the value of "name" is returning as "undefined" four times. JavaScript: for(var i = 0; i < customer.users ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

Retrieve a collection of JSON files using a single function

The format of JSON links is as follows: www.example.com/link-number-end-of-link.com.json I need to retrieve multiple JSON link files where the only variable changing is the number in the link. For example, it could range from 10 to 40, with the first ...

What is the best way to incorporate Blade code into a React component within a Blade view file?

Recently, I've been working on a Laravel view named homepage.blade.php, which includes the following code: <body> <div id=root></div> <script src="./js/app.js"></script> </body> In the app.js file: ...

Create your own unique Semantic UI themes using the Semantic UI theme builder, complete with support for Font Awesome classnames and the ability to preview them with the

My admiration for Semantic UI and Semantic UI React knows no bounds. Not only are they phenomenal libraries, but their documentation is truly a work of art. Yet, crafting and keeping up with themes for these components can be quite the challenge. The task ...

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...

Utilize array.prototype.reduce() with strings

I'm puzzled about how the reduce operation is carried out on a string. Initially, a new Str instance is created with the desired string as a parameter. Following that, the split method is used to divide the string into an array of strings. A method c ...

Switching between different months in the React-Calendar display

I've been working with React-Calendar and I'm facing an issue where the month doesn't change when clicking the navigation arrows in the calendar. Here's a snippet of my code: ... const onActiveStartDateChangeHandler = ({ activeStartDa ...

Implementing Laravel's functionality for calculating average ratings with the help of jQuery

In my database, I have two tables named Users and ratings. The Users can give ratings to consultants, and the Ratings table structure is as follows: User_id | consultant_id | rating --------------------------------- 1 1 2 ...

Error: React cannot render objects as children

I am encountering an error that I cannot seem to figure out. The issue seems to be with the following line of code: <p className="bold blue padding-left-30">{question}</p> Specifically, it does not like the usage of {question} in the above pa ...

What is the best way to accomplish this task with ajax?

Hello, I'm new to using ajax and jquery. Could someone please explain how I can achieve this without page refresh? Here is my PHP code: <div class="recentwork"> <div class="imgholderfloat"> <?php include 'process/connect.php' ...