Route ::使用Laravel 5.5+中的通配符重定向 [英] Route::redirect with wildcard in Laravel 5.5+

查看:107
本文介绍了Route ::使用Laravel 5.5+中的通配符重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel 5.5中引入的新Route::redirect是实用的,但是它允许使用{any}通配符吗?

The new Route::redirect introduced in Laravel 5.5 is practical, but does it allow {any} wildcard?

这是我在Laravel 5.4中曾经做过的事情

Here is what I used to do in Laravel 5.4

Route::get('slug', function () {
    return redirect('new-slug', 301);
});

在Laravel 5.5中,我可以执行以下操作:

In Laravel 5.5, I can do the following:

Route::redirect('slug', url('new-slug'), 301);

通过除去闭包允许路由缓存.

Which allows route caching by getting rid of the closure.

到目前为止很好,但是如果我想使用通配符怎么办?在Laravel 5.4中,我可以这样做:

So far so good, but what if I want to use a wildcard? In Laravel 5.4, I could do:

Route::get('slug/{any}', function ($any) {
    return redirect('new-slug/'.$any, 301);
});

当然,我仍然可以在Laravel 5.5中使用它,但是我的意思是能够缓存我的路由文件.

Of course, I can still use this in Laravel 5.5, but my point is to be able to cache my route files.

新的Route::redirect是否允许使用通配符,还是我唯一的使用控制器的选项?

Does the new Route::redirect allow the use of a wildcard, or is my only option to use a controller?

编辑:我正在尝试执行以下操作:

What I am attempting to do is something like this:

Route::redirect('slug/{any}', url('new-slug/'.$any), 301);

这当然是行不通的,因为我不知道在何处引用$any变量.

Which of course doesn't work because I don't know where to reference the $any variable.

推荐答案

您可以使用:

Route::redirect('slug/{any}', url('new-slug', Request::segment(2)), 301);

如果您需要重定向输入数据:

If you need to redirect with input data:

Route::redirect('slug/{any}', str_replace_first('slug', 'new-slug', Request::fullUrl()), 301);

请注意,尽管与slug/{any}不匹配,但在每个请求中都会调用上述功能url() Request::segment(2) str_replace_first,不用担心,但是在这种情况下我更喜欢创建自己的控制器或添加直接在Web服务器中进行重定向.

Note that the above functions url() Request::segment(2) str_replace_first will be called in each request although there is no match for slug/{any}, nothing to worry about but I prefer to create my own controller in this case or add the redirect in the web server directly.

这篇关于Route ::使用Laravel 5.5+中的通配符重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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