简体   繁体   English

Laravel 6 允许在路由参数上传递“null”

[英]Laravel 6 allow "null" to be passed on route parameter

I'm using Laravel 5.5 and upgrading to Laravel 6.0.我正在使用 Laravel 5.5 并升级到 Laravel 6.0。
There are numerous codes that goes like this in the project:项目中有很多这样的代码:

 route('some_route_name', optional($someobject)->id)

Laravel 5.5 can have null passed on that route above and not throwing an error. Laravel 5.5 可以在上面的路由上传递null并且不会抛出错误。 Now it returns this error below because most of the time the value is null现在它在下面返回此错误,因为大多数情况下该值为null

Missing required parameters for [Route: some_route_name] 

Now I have to replace all occurrences of the code above with:现在我必须将上面所有出现的代码替换为:

 route('some_route_name', optional($someobject)->id ?: 0)

Is there any way to accept "null" as route parameters?有没有办法接受“null”作为路由参数?
Or maybe this is bad practice in general?或者这通常是不好的做法?

Simply, in your route just put one question mark简单地说,在你的路线上加一个问号

route('some_route_name/{id?}','Controller@show');

Then in your controller然后在你的控制器中

public function show($id = null)

Or if you bind with the Model, change your route to或者,如果您与模型绑定,请将您的路线更改为

route('some_route_name/{user?}','Controller@show');

And your controller will be like this你的控制器会是这样的

 public function show(User $user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM