basagabi basagabi - 8 months ago 136
PHP Question

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.


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

Answer Source

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);
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download