【问题标题】:Deleting record data in Laravel is not working在 Laravel 中删除记录数据不起作用
【发布时间】:2021-04-04 00:28:05
【问题描述】:

我是 Laravel 编程的新手。我已经搜索了很多关于删除功能的资源,但它不起作用。当我单击删除按钮时,它只显示 404 NOT FOUND。我正在使用 Laravel 7.0。希望你能帮我解决它。谢谢!

这里

/**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $student = Student::find($id);
        $student->delete();
        return redirect('/');
    }

这是我的路线:

Route::get('/delete/{id}','StudentController@destroy');

这是我的观点:

<table class="table thead-light">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Mã sinh viên</th>
      <th scope="col">Khối</th>
      <th scope="col">Tên lớp</th>
      <th scope="col">Họ và Tên</th>
      <th scope="col">Thầy/Cô giáo chủ nhiệm</th>
      <th scope="col">Tính năng</th>
    </tr>
  </thead>
  <tbody>
    @foreach($students as $student)
    <tr>
        <th scope="row">{{ $student->id }}</th>
        <td>{{ $student->student_id }}</td>
        <td>{{ $student->grade }}</td>
        <td>{{ $student->class }}</td>
        <td>{{ $student->fullname }}</td>
        <td>{{ $student->head_teacher }}</td>
        <td id="functions">           
          <a href="#" class="btn btn-info">Xem hồ sơ</a> 
            <a href="{{ url('/edit/'.$student->id) }}" class="btn btn-warning">Sửa</a>
            <a href='delete/{{ $student->id }}' class="btn btn-danger">Xóa</a>
        </td>
    </tr>    
    @endforeach  
    </tbody>
</table>

【问题讨论】:

  • 尝试使用Route::delete()。您正在向需要 DELETE 请求的方法发送 GET 请求。 Documentation
  • &lt;a href='delete/{{ $student-&gt;id }}',试试用斜杠前缀&lt;a href='/delete/{{ $student-&gt;id }}'

标签: php laravel


【解决方案1】:

另一条路线可能会覆盖您的删除路线。

对于删除操作,您应该使用 HTTP Delete 请求而不是 Get

Route::delete('/delete/{id}','StudentController@destroy');
<form action="/delete/{{ $student->id }}" method="POST">
    @csrf
    @method('DELETE')
    <button type="submit">Delete</button>
</form>

【讨论】:

  • 是的,我试过了,但问题仍然出现“404 NOT FOUND”
【解决方案2】:

您的删除链接不正确。您应该使用命名路由。

为您的路线

Route::get('/delete/{id}','StudentController@destroy')->name('delete.student');

对于视图中的链接

<a href='{{ route('delete.student', $student->id) }}' class="btn btn-danger">Xóa</a>

考虑更改您的编辑链接。尽量不要使用 url() 作为链接,使用命名路由。

【讨论】:

  • 是的,我试过了,但它引发了一个异常“Route [delete.student] not defined。(查看:D:\Xampp\htdocs\ems_project\resources\views\studentlists.blade. php)"
  • 尝试清除您的路由缓存。如果你的 route.php 文件中有它,它不应该说未定义
【解决方案3】:

好吧,我找到了解决问题的方法。我刚刚参考了这篇文章:404 Not Found, but route exist in Laravel 5.4。简而言之,我应该使用“php artisan route:clear”和“php artisan route:list”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多