2
votes

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
I just tested and it works (5.6 though) so i think 5.5 won't be an issue either. Edit: 5.5 also worksIndra
@Indra I have updated my question to show you what I am trying to doPimar
You mean artisan route:cache? Yes it’ll still workZoe Edwards
@ThomasEdwards It works indeed, but my question was about using Route::redirect with a wildcard in Laravel 5.5+. Route::redirect('slug/{any}', url('new-slug/'.$any), 301); doesn't work, since $any is not specified anywhere.Pimar
I think it's gonna work. Try checking this PR github.com/laravel/ideas/issues/654Indra

1 Answers

4
votes

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.