Laravel中Yajra DataTable数据删除与路由参数错误解决
Hey there! Let's work through your two Laravel + Yajra DataTables questions step by step.
Here's a complete breakdown to get the delete feature working smoothly:
Step 1: Confirm your route setup
You already haveRoute::resource('plane', 'PlaneController');which is perfect—this automatically creates thedestroyroute (aDELETEendpoint at/plane/{plane}) that handles deletion requests.Step 2: Keep your delete button markup
Your currentaddColumn('action')code correctly adds a delete button with adata-idattribute to pass the plane's ID. No changes needed here, just ensure thedeleteItemclass is consistent for targeting in your JS.Step 3: Write the corrected AJAX delete handler
Your existing JS has a small issue with URL construction (we'll fix that in the next section), but here's the polished version that includes CSRF protection and proper confirmation:$('body').on('click', '.deleteItem', function () { var planeId = $(this).data("id"); // Only proceed if user confirms deletion if (confirm("Are you sure you want to delete this plane?")) { $.ajax({ type: "DELETE", url: "/plane/" + planeId, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, success: function (data) { table.draw(); // Refresh the DataTable after deletion alert("Plane deleted successfully!"); // Optional success feedback }, error: function (xhr) { console.log('Error:', xhr.responseText); } }); } });Don't forget to include the CSRF token in your layout's
<head>(required for DELETE requests):<meta name="csrf-token" content="{{ csrf_token() }}">Step 4: Add the
destroymethod to your PlaneController
Handle the deletion request in your controller with Laravel's route model binding:public function destroy(Plane $plane) { $plane->delete(); return response()->json(['success' => 'Plane deleted successfully!']); }Laravel will automatically fetch the correct Plane instance using the ID passed in the URL.
Let's diagnose and fix this common route error:
What's causing the issue?
Your error message references the URI plane/{plane}/id—this isn't the default structure for a resource route's destroy endpoint. Normally, Route::resource('plane', 'PlaneController') creates a DELETE route at /plane/{plane} (only one parameter: the plane's ID).
The main problem is in your JS URL construction:
url: "{{ route('plane.destroy') }}"+'/'+id,
The route('plane.destroy') helper requires you to pass the plane ID as a parameter because the route expects {plane}. Skipping this parameter triggers the missing parameters error.
How to fix it?
You have two solid options to construct the correct URL:
Option 1: Use the route helper with a placeholder
Since you can't pass a JS variable directly to the Blade route helper, use a placeholder and replace it dynamically:
var deleteUrl = "{{ route('plane.destroy', ':id') }}".replace(':id', planeId);
Then use deleteUrl as the url value in your AJAX call.
Option 2: Directly construct the URL
Skip the route helper entirely and build the URL manually (simple and reliable):
url: "/plane/" + planeId,
Bonus: Check for custom route overrides
If your route URI is indeed plane/{plane}/id, you might have a custom route in web.php that's overriding the resource route. Double-check for lines like this:
// This would create the non-standard URI causing your error Route::delete('plane/{plane}/id', 'PlaneController@destroy')->name('plane.destroy');
If you find this, remove it and stick to the standard resource route for RESTful consistency.
Final corrected JS code
Here's the full working delete handler with the route helper fix:
$('body').on('click', '.deleteItem', function () { var planeId = $(this).data("id"); if (confirm("Are you sure you want to delete this plane?")) { var deleteUrl = "{{ route('plane.destroy', ':id') }}".replace(':id', planeId); $.ajax({ type: "DELETE", url: deleteUrl, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, success: function (data) { table.draw(); alert(data.success); }, error: function (xhr) { console.log('Error:', xhr.responseText); } }); } });
内容的提问来源于stack exchange,提问作者Tabish

