douyaosi3164
2018-01-22 22:34
浏览 32
已采纳

Laravel静态可选路由

I am looking for a "quick" and "clean" solution to the usual http://project.name/products/total where total is optional.

I've tried so far this:

Route::get('products/{total?}', 'ProductController@get', function ($total = null) {});

And then $products = ($total == null) ? Product::all() : Product::count();

But this not only works with products/total but products/whatever. I think adding if($total = 'total') is not a good practice.

I want the last parameter to be static, I am not thinking straight. I guess I have to avoid defining two Routes (Route::get('products'... and Route::get('products/total'...

Laravel Documentation is not helping either. What am I doing wrong?

图片转代码服务由CSDN问答提供 功能建议

我正在寻找通常 http://project.name/products/total 其中总计是可选的。

到目前为止我已经尝试了这个:

  Route :: get('products / {total?}','ProductController @  get',function($ total = null){}); 
   
 
 

然后 $ products =($ total == null)? Product :: all():Product :: count();

但这不仅适用于产品/总计,还适用于产品 /不管即可。 我认为添加 if($ total ='total')不是一个好习惯。

我希望最后一个参数是静态的,我不是在考虑 直行。 我想我必须避免定义两个路由( Route :: get('products'... Route :: get('products / total'... < / p>

Laravel Documentation 不是 我也做错了什么?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongxiaoying5882 2018-01-22 22:51
    已采纳

    If your routes are in reality doing different things (even if they are quite similar) then you should probably add two different routes.

    Route::get('products', function () {
          Product::all() 
    });
    
    Route::get('products/total', function () {
          Product::count() 
    });
    

    Of course this does imply that if there's code that's shared between the two routes you can move it to its own helper function/class.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题