php 删除过程中出现错误“...未定义路由[users.index]”

tktrz96b  于 2023-05-16  发布在  PHP
关注(0)|答案(1)|浏览(375)

我正在使用Laravel 8,在处理页面时发生错误。我尝试执行删除按钮,但出现错误
Symfony\Component\Routing\Exception\RouteNotFoundException Route [users.index]未定义。
如何解决此问题,删除用户的最佳方法是什么?谢谢你

UserController
public function destroy($id){
    $users = User::where('id',$id)->first();
    $users -> delete();

    return redirect()->route('users.index')
        ->with('success','User deleted successfully');
}
用户路由
Route::group(['prefix' => '/users',  'middleware' => 'user'], function() use ($router)
{
Route::get('', [UserController::class, 'index']);
Route::get('/{id}/delete',[UserController::class, 'destroy'])->name('users.destroy');
});
用户页面
<table class="table">
    <thead>
      <tr>
        <th width='10%'>ID</th>
        <th width='20%'>Name</th>
        <th width='20%'>Email</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
    @foreach($users as $user)
       <tr>
          <td>{{ $user->id }}</td>
          <td>{{ $user->name }}</td>
          <td>{{ $user->email }}</td>
          
          <td>
             <!-- Edit -->
             <a href="" class="btn btn-sm btn-primary">Show</a>
             <!-- Edit -->
             <a href="" class="btn btn-sm btn-info">Edit</a>
             <!-- Delete -->
             <a href="{{ route('users.destroy',$user->id) }}" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this user?')">Delete</a>

          </td>
       </tr>
    @endforeach
    </tbody>
 </table>
wqlqzqxt

wqlqzqxt1#

错误消息“Symfony\Component\Routing\Exception\RouteNotFoundException Route [users.index] not defined”表示在应用程序的路由配置中未定义路由名称“users.index”。
要解决此问题,请添加路由名称:

Route::get('/', [UserController::class, 'index'])->name('users.index');

这将在删除用户后将用户重定向到正确的路由。
关于删除用户的最佳方法,您所使用的方法很好。您已经使用where()方法按ID获取了用户,并使用delete()方法将其删除。但是,您可以通过使用find()方法来简化此代码,直接通过ID获取用户并在一行代码中删除它:

public function destroy($id){
    User::find($id)->delete();
    return redirect()->route('users.index')->with('success','User deleted successfully');
}

已更新
另一种删除方法是使用Laravel中的软删除功能,该功能将记录标记为已删除,但将其保留在数据库中,以防以后需要恢复。您可以在模型中使用softDeletes trait,然后使用delete方法软删除记录,而不是永久删除它。

相关问题