4

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.

pimarc
  • 3,621
  • 9
  • 42
  • 70
  • I just tested and it works (5.6 though) so i think 5.5 won't be an issue either. Edit: 5.5 also works – Indra Apr 03 '18 at 15:24
  • @Indra I have updated my question to show you what I am trying to do – pimarc Apr 03 '18 at 15:39
  • You mean `artisan route:cache`? Yes it’ll still work – Zoe Edwards Apr 03 '18 at 15:44
  • @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. – pimarc Apr 03 '18 at 16:03
  • I think it's gonna work. Try checking this PR https://github.com/laravel/ideas/issues/654 – Indra Apr 03 '18 at 16:55

1 Answers1

5

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.

Razor
  • 9,577
  • 3
  • 36
  • 51