Laravel中通过按钮删除数据行无响应问题求助
Hey there! Let's get that delete button working properly. The main reason it's not doing anything right now is that your submit button isn't wrapped in a <form> element, and Laravel requires a specific HTTP method to handle delete operations correctly.
Here's what you need to adjust in your view code:
Wrap your delete button and CSRF token inside a form that points to your destroy route, and add the DELETE method spoofing directive:
@foreach ($scores as $score) <tr> <td>{{ $score->id }}</td> <td>{{ $score->serialnumber }}</td> <td>{{ $score->name }}</td> <td>{{ $score->created_at }}</td> <td></td> <td> <!-- Add the form wrapper here --> <form action="{{ route('cd.destroy', $score) }}" method="POST"> @csrf <!-- This replaces your csrf_field() --> @method('DELETE') <!-- Required for Laravel's resource destroy method --> <button class="btn btn-danger" type="submit">Delete this Row</button> </form> </td> </tr> @endforeach
Key explanations:
- Form wrapper: Without a form, clicking the button has no destination to send the request to—this is why nothing happens right now.
- @method('DELETE'): HTML forms don't natively support
DELETErequests, so Laravel uses this directive to generate a hidden input that tells the framework to treat the request as aDELETEoperation, which matches your controller'sdestroymethod (assuming you're using resource routes). - Route targeting:
route('cd.destroy', $score)generates the correct URL for deleting the specific$scorerecord—make sure your routes are set up withRoute::resource('cd', YourController::class);for this to work.
Your controller code looks good as-is:
public function destroy($delete) { $delete->delete(); return redirect()->route('cd.index')->with('success','deleted successfully!'); }
Once you update the view, your delete button should trigger the request properly and redirect you back with the success message.
内容的提问来源于stack exchange,提问作者Devi
相关产品推荐
相关产品推荐

