5

I have this code on my routes.php file that do a redirect. Though the problem is that whenever I ran php artisan route:cache command, it gives me an error of Unable to prepare route [article/{params}] for serialization. Uses Closure.

I know this has something to do with routes not allowing it to be cached if it have a closure. But how could I make a workaround for this redirect?

Route::get('article/{params}', function($params) {
    return Redirect::to($params, 301);
});
basagabi
  • 4,900
  • 6
  • 38
  • 84

3 Answers3

7

Since Laravel 5.5 you can use:

Route::redirect('/here', '/there', 301);

See the documentation under Redirect Routes.

Marian Nasry
  • 821
  • 9
  • 22
thijsai
  • 1,795
  • 1
  • 18
  • 26
4

Route caching does not work with Closure based routes. To use route caching, you must convert any Closure routes to use controller classes.

Route::get('article/{params}', 'HelperController@redirect');

in your controller you can have your redirect function like below:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HelperController extends Controller
{
  public function redirect($params)
  {
    return Redirect::to($params, 301);
  }
}
Can Celik
  • 2,050
  • 21
  • 30
  • Would someone possibly know how to do this scenario wherein it will pass arguments to the controller? `Route::get('articles/{params}', function($params) { return Redirect::to('articles/' . $params . '/edit', 301); });` The `articles/` should be an argument that could be pass on to the controller so that I can just have one(1) controller that does redirect. This is because I have several of this lines that just do the same functionality and I do not want to create specific controllers for each redirect. It must be a dynamic controller that can accept parameters. – basagabi Feb 25 '16 at 17:51
4

It appears that caching routes now also works with Closures.

The warning in the docs is also gone from Laravel 7:
https://laravel.com/docs/7.x/controllers#route-caching
to Laravel 8:
https://laravel.com/docs/8.x/routing#route-caching

Tested it also in a project and it does not complain.

Ratto
  • 137
  • 1
  • 8
Tobias Gepp
  • 141
  • 1
  • 4