如何覆盖laravel资源路由?

时间:2018-06-19 09:23:59

标签: laravel-5.6

我不认为这篇文章How do I override laravel resource route default method?解决了我的问题。

正常资源路由是“index”显示所有项目。我想要做的是让“index”显示特定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);
    ...
}

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

<a href="{{route('attendees.index', ['classroom' => $data->id])}}">{{$data->Reference}}
  • 据我所见,我将参数传递给控制器​​。
  • 并且控制器设置为期望$ id参数

那我为什么要这个呢?我猜的是一些非常基本的东西,但我看不清楚。

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

2 个答案:

答案 0 :(得分:0)

因为您只传入了1个参数。方法&#34;索引&#34;在控制器中期待2个参数。您可能想检查您的route.php文件。 https://laravel.com/docs/5.6/routing

答案 1 :(得分:0)

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

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

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

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

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

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