Hello, I'm developing an API using laravel, so definitely I don't want to use the cookies. However, I do want to use the sessions mechanism for APIs that require authentication.
So, I'm using the sessions.driver = "file"
To be able to use the mechanism, but allow to override the cookie set, after much debugging, I found out that there is some hardwiring at the Middleware class, but through the magic of filters, you can disable the feature right before the cookie is set.
So, on filters.php
, I created the following filter, and added as an after
filter of my route group
/*
|--------------------------------------------------------------------------
| Custom Filter to remove the session cookie
|--------------------------------------------------------------------------
|
| By default, if session driver is other than `null` or `array`, it will
| create a cookie and pass the encrypted session id so that it can be used
| across web requests.
| However, since our application is an API, we dont need the cookie, but
| we still want to be able to use the session functionality, so to allow
| this, we just need to set the driver to `array` right before the
| dispatcher gets to the point to add the session cookie.
|
| This is the Laravel call stack
| \Illuminate\Session\Middleware::handle()
| -> \Illuminate\Session\Middleware::addCookieToResponse()
| -> \Illuminate\Session\Middleware::sessionIsPersistent()
|
| All session handling and file storage has happened before sessionIsPersistent()
| is called, so we are safe to add an `after` filter that will reset
| the driver in the configuration and thus preventing this specific
| cookie to be added, all other previously added cookies will be
| kept (if any added) and thus sent as part of the response.
*/
Route::filter('session.cookie.remove', function(){
// Has to be 'array' because null, will prevent from writing sessions
Config::set('session.driver', 'array');
});
Note: the only case where this filter will not get call and thus producing the cookie, is if an exception occurs, in which case you may want to update the config on your error handler as well (default error handler if you haven't overwritten laravel's).
To override, look at app/start/global.php
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community