如何覆盖 laravel 资源路由?

How do I override a laravel resource route?

我认为 post 不能解决我的问题。

正常的资源路线是"index"显示所有物品。我想要做的是让 "index" 显示特定 ID 的所有 相关 项目。

因此,当我 select 列表中的一个教室时,我希望我正在调用的索引操作显示该特定教室的所有人员,因为它是索引功能。

所以我更换了默认的资源路由

//Route::resources(['attendees' => 'attendeesController']);

Route::resource('attendees', 'attendeesController')->names([
    'index'   => 'attendees.index',
    'store'   => 'attendees.store',
    'create'  => 'attendees.create',
    'show'    => 'attendees.evaluation',
    'update'  => 'attendees.update',
    'destroy' => 'attendees.destroy',
    'edit'    => 'attendees.edit',
]);

所以在我的控制器中,我有这个:

public function index(Request $request,$id)
{
    dd($request);
    ...
}

在我对教室的看法中,在特定的教室 ID 上我有这个

<a href="{{route('attendees.index', ['classroom' => $data->id])}}">{{$data->Reference}}

为什么我会收到这个?我在猜测一些非常基本的东西,但我看不出是什么。

Type error: Too few arguments to function
App\Http\Controllers\AttendeesController::index(), 
1 passed and exactly 2 expected

因为你只传入了1个参数。控制器中的方法 "index" 需要 2 个参数。您可能需要检查 route.php 文件。 https://laravel.com/docs/5.6/routing

默认情况下,索引操作需要一个$id,因此您可以将其设置为空

public function index(Request $request,$id = null)

此外,如果您想根据文档获取特定 $id 的相关项目,URL 将是 attendees/123,它将被重定向到 show 函数。因此,您还需要编辑该路线。而不是尝试将查询参数传递给索引路由并使用查询参数,您可以获得相关数据。 代替 attendees/123 会是 attendees?id=123

查询参数设置为显示相关项,否则显示索引。 如果您仍然想通过索引实现它,您需要更改如下路线

Route::resource('attendees', 'AttendeesController',['only' => ['index', 'create', 'store']]);

Route::get('/attendees/{id}', 'AttendeesController@index');