简体   繁体   English

Laravel 路由重定向,无需关闭路由缓存

[英]Laravel route redirect without closure for route cache

I have this code on my routes.php file that do a redirect.我的routes.php文件中有这段代码可以进行重定向。 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.虽然问题是每当我运行php artisan route:cache命令时,它都会给我一个错误: 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:Laravel 5.5您可以使用:

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

Tested it also in a project and it does not complain.在一个项目中也对其进行了测试,它没有抱怨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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