dongxibo2095 2017-05-03 00:04
浏览 622
已采纳

Laravel 5路由中有多个可选参数

I have a problem with Laravel 5, and to be precise, I can't find the solution for it. In C# (ASP.NET MVC) it's easy to solve. For example, I have these routes (I'll just type the route content, and the function header, for the sake of simplicity)

/{category}/Page{page}
/Page{page}
/{category}

The function is defined inside Product controller. function header looks like this:

public function list($page = 1, $category = null)

the problem is, whenever I enter just one argument, it doesn't send the value for the parameter by the name I set in the route, but rather, it pushes values by function parameter order. So, when I open /Page1, it works properly, value of 1 is sent to $page variable, but when I access /Golf(made up on the spot), it also sends the value to the $page variable. Any possible idea how to avoid this, or do I really need to make different functions to handle these cases?

In C#, it properly sends the value, and keeps the default value for undefined parameter.

Hope you have an answer for me. Thank you in advance and have a nice day :)

  • 写回答

2条回答 默认 最新

  • douzhenchun6782 2017-05-03 03:12
    关注

    So, as you've seen the parameters are passed to the function in order, not by name.

    To achieve what you want, you can access these route parameters from within your function by type hinting the request object to it like this:

    class ProductController extends Controller
    {
        function list(Request $request){  # <----------- don't pass the params, just the request object
    
            $page = $request->route('page');   # <--- Then access by name
            $category = $request->route('category');
    
            dd("Page: $page | Category: $category");
        }
    }
    

    Then of course you would set all 3 of your routes to hit that same controller method:

    Route::get('/{category}/Page{page}', 'ProductController@list');
    Route::get('/Page{page}', 'ProductController@list');
    Route::get('/{category}', 'ProductController@list');
    

    Hope this helps..!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!