laravel-5.6 - 如何覆盖 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}}
- 据我所见,我正在将参数传递给控制器。
- 并且控制器设置为期望 $id 参数
那我为什么会得到这个?我猜一些非常基本的东西,但我看不出是什么。
Type error: Too few arguments to function
App\Http\Controllers\AttendeesController::index(),
1 passed and exactly 2 expected
解决方案
默认情况下,索引操作需要一个$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');
推荐阅读
- java - Dali Java Persistence Tools - 数据库数据类型到 Java 数据类型的映射
- php - 如果登录,Symfony 跳过 API 的 JWT 身份验证
- php - 计算另一个连接表中的行数
- django - 如何使用循环从 Django 中的 html 模板请求
- powershell - 我的 Powershell 脚本不做多线程工作,为什么?
- c# - 在 docker 容器内对字符串进行测试失败
- mysql - 当文件不存在时,Mysql“LOAD DATA LOCAL INFILE”不应该停止执行
- python-3.x - 仅当我重新启动 shell 窗口时更新外部文件中的值才有效
- split - 如何在 forEach 循环中拆分 innerHTML 字符串并从两个子字符串中提取输出
- javascript - Firebase Firestore:如何更新或访问和更新地图、数组、文档、集合中的字段值