首页 > 解决方案 > 如何覆盖 laravel 资源路由?

问题描述

我不认为这篇文章如何覆盖 laravel 资源路由默认方法?解决了我的问题。

正常的资源路线是“索引”显示所有项目。我想要做的是让“索引”显示特定 ID 的所有相关项目。

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

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

//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

标签: laravel-5.6

解决方案


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

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');

推荐阅读