Laravel 5路由中的多个可选参数 [英] Laravel 5 multiple optional parameters in route

查看:925
本文介绍了Laravel 5路由中的多个可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Laravel 5有问题,确切地说,我找不到解决方案. 在C#(ASP.NET MVC)中,它很容易解决. 例如,我有这些路由(为简单起见,我只键入路由内容和函数标头)

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)

问题是,每当我仅输入一个参数时,它都不会按照我在路由中设置的名称发送参数的值,而是按函数参数的顺序推入值. 因此,当我打开/Page1时,它可以正常工作,将值1发送到$ page变量, 但是当我访问/Golf(当场创建)时,它也会将该值发送到$ page变量. 任何可能的想法如何避免这种情况,还是我真的需要提供不同的功能来处理这些情况?

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?

在C#中,它将正确发送该值,并保留未定义参数的默认值.

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 :)

推荐答案

因此,如您所见,参数是按顺序而不是按名称传递给函数的.

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");
    }
}

然后,您当然可以将所有3条路线设置为使用相同的控制器方法:

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..!

这篇关于Laravel 5路由中的多个可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆