Laravel 路由重定向而不关闭路由缓存

Laravel route redirect without closure for route cache

我的 routes.php 文件中有这段代码可以执行重定向。虽然问题是每当我 运行 php artisan route:cache 命令时,它都会给我一个 Unable to prepare route [article/{params}] for serialization. Uses Closure.

的错误

我知道这与路由在关闭时不允许缓存有关。但是我该如何解决此重定向?

Route::get('article/{params}', function($params) {
    return Redirect::to($params, 301);
});

路由缓存不适用于基于闭包的路由。要使用路由缓存,您必须将任何 Closure 路由转换为使用控制器 类.

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

在您的控制器中,您可以使用如下的重定向功能:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HelperController extends Controller
{
  public function redirect($params)
  {
    return Redirect::to($params, 301);
  }
}

因为 Laravel 5.5 您可以使用:

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

查看重定向路由下的documentation

看来缓存路由现在也适用于闭包。

文档中的警告也从 Laravel 7:
消失了 https://laravel.com/docs/7.x/controllers#route-caching
到 Laravel 8:
https://laravel.com/docs/8.x/routing#route-caching

也在一个项目中测试了它,它没有抱怨。