Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable "Cookie" header when responding json

Tags:

laravel-5

I'd like to disable (remove) "Cookie" header when responding as json. Actually I could set Config::set('session.driver', 'array') on filter with Laravel 4.2.

If I did in L5 (version 5.0.5), I got following error at log file.

[YYYY-MM-DD ..:..:..] local.ERROR: exception 'ErrorException' with message 'Undefined index: _sf2_meta' in /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Store.php:280
Stack trace:
#0 /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Store.php(280): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined index...', '/foo/bar/ve...', 280, Array)
#1 /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Store.php(251): Illuminate\Session\Store->addBagDataToSession()
#2 /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(89): Illuminate\Session\Store->save()
#3 /foo/bar/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(129): Illuminate\Session\Middleware\StartSession->terminate(Object(Illuminate\Http\Request), Object(Illuminate\Http\JsonResponse))
#4 /foo/bar/public/index.php(57): Illuminate\Foundation\Http\Kernel->terminate(Object(Illuminate\Http\Request), Object(Illuminate\Http\JsonResponse))
#5 {main}
like image 931
hide.h Avatar asked Oct 19 '22 17:10

hide.h


1 Answers

Ok, it turns out, that it is no longer possible to change session/cookie driver within route middlewares. You have to specify the middleware BEFORE Illuminate\Session\Middleware\StartSession middleware.

Solution: 1. Create your own middleware:

class ApiSession implements Middleware{
    public function handle($request, Closure $next){
        $path = $request->getPathInfo();

        if(strpos($path, '/api/') === 0){
            \Config::set('session.driver', 'array');
            \Config::set('cookie.driver', 'array');
        }

        return $next($request);
    }
}
  1. Add it in Kernel file (app/Http/Kernel.php) before Session middleware:

[..] ApiSession::class, // Check if an API request. If so, set session, cookie drivers Illuminate\Session\Middleware\StartSession::class, [..]

The bad part is that you cannot use it with route groups. You have to check for your self if this middleware is applied by checking the current url path.

like image 98
Mārtiņš Briedis Avatar answered Oct 27 '22 08:10

Mārtiņš Briedis