首页 > 解决方案 > 我在使用 Laravel 创建一些基本过滤时遇到问题

问题描述

我的索引页面显示了我的图像表中的所有图像,最新提交的图像位于顶部。我正在尝试添加一些基本过滤,以便我可以掌握这个概念,但我做错了。我的想法是:

添加 2 个<a>带有 URL 的元素到www.domain.comwww.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/adminor之类的 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');

因此,即使我转到标签路线,也会显示索引视图而不是标签视图。

如果有人能启发我如何实现这个基本过滤,我将不胜感激。

标签: phplaravellaravel-5

解决方案


你可以这样做 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]);
}

推荐阅读