Route::redirect with wildcard in Laravel 5.5+

2019-07-15 02:06发布

问题:

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

Here is what I used to do in Laravel 5.4

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

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.

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

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

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

EDIT: What I am attempting to do is something like this:

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

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

回答1:

You may use:

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

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.