laravel Unable to prepare route ... for serialization. Uses Closure

Francesco picture Francesco · Jul 23, 2017 · Viewed 115.3k times · Source

When I clear caches in my Laravel 5.2 project, I see this error message:

[LogicException] Unable to prepare route [panel] for serialization. Uses Closure.

I think that it's related with a route

Route::get('/article/{slug}', 'Front@slug');

associated with a particular method in my controller:

public function slug($slug) {
    $article = Article::where('slug',$slug)->first();

    $id = $article ->id_article ;

    if ( ($article=== null) || (is_null($id)) ) return view('errors/Db');

    else return view('detail')->with(array('article'=> $article,  'title'=>'My title - '.$article->title)); 
}`

In short, from a master view I pass $slug, that is a shortlink to the article, with $slug , which is unique in the database, I identify the record and then I pass it's contents to the detail view.

I didn't have any problem when I wrote the method, infact it worked like a charm, but after I cleaned caches, I get that error and the links in the master view don't show any shortcode.

Where am I doing wrong?

Answer

tkausl picture tkausl · Jul 23, 2017

I think that it's related with a route

Route::get('/article/{slug}', 'Front@slug');

associated with a particular method in my controller:

No, thats not it. The error message is coming from the route:cache command, not sure why clearing the cache calls this automatically.

The problem is a route which uses a Closure instead of a controller, which looks something like this:

//                       Thats the Closure
//                             v 
Route::get('/some/route', function() {
    return 'Hello World';
});

Since Closures can not be serialized, you can not cache your routes when you have routes which use closures.