【问题标题】:Passing Optional parameters not calling to the correct one传递可选参数而不调用正确的参数
【发布时间】:2015-08-24 11:14:21
【问题描述】:

参数很少卡住,市场和排序是可选的

Route::get('Category/{title}/{market?}/{sort?}', 'HomeController@productList');

但是当我在 URI 中这样做时

网址:类别/标题/?sort=3

它没有注册为 3 进行排序,而是作为市场参数进入

当然,如果 URI 是 Category/title/Makert/3,它将返回我想要的内容

public function productList($title, $market = null, $sort = null)
{
    // Gets the Categories with its Markets
    $categorys= Product::cats();
    $brands = Product::CategoryWithMarket($title, $market)->groupBy('Brand')->get();
    $subCat = Product::where('Category', $title)->groupBy('Market')->orderBy('Market', 'ASC')->get();

    if (!$market) {
        $marketList = Product::where('Category', $title)->orderBy('Brand', 'ASC')->orderBy('Label', 'ASC')->paginate(15);
        $brands     = Product::where('Category', $title)->groupBy('Brand')->orderBy('Brand', 'ASC')->get();
        $mainTitle  = ucfirst($title);
    }

    else {
        // Gets the list of products with the catery and market attributes arranged by the brand of product
        $marketList = Product::CategoryWithMarket($title, $market)->paginate(15);
        $mainTitle =  ucfirst($title) . ' ' . ucfirst($market) ;
    }

    return $sort;

理论上它应该传回排序参数 3 但它不返回任何内容,所以我的问题是我如何让排序返回其值 3 而不是 null

【问题讨论】:

    标签: php laravel laravel-5 optional-parameters


    【解决方案1】:

    Router 仅使用路径来匹配路由,并且仅将路径参数注入控制器。因此,如果您希望将 sort 从路由器传递给控制器​​,则需要将其放在路径 (/{sort?}) 中,而不是查询中 ( ?sort=3)。

    如果您想访问控制器中的查询参数,您可以通过 $request 对象(如果它是您的操作的参数)或 Request 外观:

    public function someAction() {
      echo Request::query('sort');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2013-03-14
      相关资源
      最近更新 更多