php - 我在使用 Laravel 创建一些基本过滤时遇到问题
问题描述
我的索引页面显示了我的图像表中的所有图像,最新提交的图像位于顶部。我正在尝试添加一些基本过滤,以便我可以掌握这个概念,但我做错了。我的想法是:
添加 2 个<a>
带有 URL 的元素到www.domain.com
和www.domain.com/ascending
。如果用户去www.domain.com
,图像将按降序显示,如果他去,图像将按www.domain.com/ascending
升序显示。
然后我让我的家庭路线Route::get('/', 'PagesController@index')->name('home');
有一个可选参数,比如Route::get('/{filter?}', 'PagesController@index')->name('home');
基于可选参数,我将向$images
视图发送不同的变量:
public function index($filter){
switch($filter) {
case 'ascending' : $images = Image::orderBy('created_at', 'asc')->get();break;
default : $images = Image::orderBy('created_at', 'desc')->get();
}
return view('home', ['images' => $images]);
}
一旦我这样做了,到目前为止我遇到了两个问题:
首先,当我去时www.domain.com
,我得到"Type error: Too few arguments to function App\Http\Controllers\PagesController::index(), 0 passed and exactly 1 expected"
其次,在将可选参数添加到路由后,Route::get('/{filter?}', 'PagesController@index')->name('home');
即使我要去像http://example.com/admin
or之类的 URL,我也会发送到我的索引页面http://example.com/albums
。
我相信会发生这种情况,因为我的代码假定/admin
并且是我的http://example.com/albums
url中的可选参数,而不是应该的单独 url。
Route::get('/{filter?}', 'PagesController@index')->name('home');
Route::get('/image/{id}', 'PagesController@specificImage')->name('specificImage');
Route::get('/tags', 'PagesController@tags')->name('tags');
因此,即使我转到标签路线,也会显示索引视图而不是标签视图。
如果有人能启发我如何实现这个基本过滤,我将不胜感激。
解决方案
你可以这样做 www.domain.com?orderby=asc
Route::get('/', 'PagesController@index')->name('home');
public function index(Request $request){
$images = array();
$images = Image::orderBy('created_at', $request->get('orderBy') ?? 'desc')->get();
return view('home', ['images' => $images]);
}
推荐阅读
- javascript - Express.js - 通过请求对象内的主体转换接口
- swift - 类似承诺的方法
- airflow - 将标记设置为成功并强制所有下游任务运行
- javascript - 如果单击发送按钮,如何防止 android 键盘隐藏 - JavaScript
- python - python中类方法中的对象类型错误
- spring - 如何更改端口 hawtio,我运行一个带有弹簧骆驼休息和其他的 megazord
- sql - 我应该使用特定的 SQL 语法为 SAP 中的 ABAP 的 AutoID 编写 SQL 吗?
- c++ - Q_PROPERTY 未将值设置为通过 qml 上的模型给出的值
- arrays - 用于匹配特定字符的正则表达式
- python - 由于“TypeError: A Future or coroutine is required”,无法在 AWS Lambda 上发出 aiohttp 请求