简体   繁体   中英

Laravel route redirect without closure for route cache

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

Since Laravel 5.5 you can use:

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

See the documentation under Redirect Routes .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM