Framework: [5.0]route:cache with Closure problem

Created on 7 Feb 2015  路  9Comments  路  Source: laravel/framework

command artisan route:cache

when met closure route:

Route::get('/', function()
{
    return 'Hello World';
});

it will fail with

exception 'LogicException' with message 'Unable to prepare route [/] for serialization. Uses Closure.'

Most helpful comment

If you're not using any api func. , you can comment
/*
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
*/
in routes/api.php

All 9 comments

Yep, that's the expected behaviour.

Laravel's source code:

    /**
     * Prepare the route instance for serialization.
     *
     * @return void
     *
     * @throws LogicException
     */
    public function prepareForSerialization()
    {
        if ($this->action['uses'] instanceof Closure)
        {
            throw new LogicException("Unable to prepare route [{$this->uri}] for serialization. Uses Closure.");
        }

        unset($this->container);

        unset($this->compiled);
    }

but ,when the app has some closure route,it means cant route cache?
has solution ?
change the app code to not use closure route,or do some others like skip cache for closure route but cache for normals?

Basically, you cannot use route caching at all if you have closures in your routes. Selective caching would defeat the object.

ok,thanks,so I will change code to not use closure route at all

It is possible, with a little creativity, to serialize a Closure. The code should be modified to allow this. I might have to submit a PR for it

AFAIK, taylor tried it before and found out that having to serialize and unserialize closure reduce the performance that you could possibly gain from using route caching.

If you're not using any api func. , you can comment
/*
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
*/
in routes/api.php

Old thread but those are just sample routes. Delete them. This is covered in the docs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jackmu95 picture jackmu95  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

shopblocks picture shopblocks  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

YannPl picture YannPl  路  3Comments