How to get rid of laravel_session cookie from Laravel application?

Viewed 6241
4 Answers

If I have specific routes that I don't want Laravel to use laravel_session. You can apply that to any routes you want.

Ex. For example, if you want to apply to only these 2 routes :

url1 or url2

Route::get('/url1', 'SampleController@fnName');

Route::get('/url2', 'SampleController@fnName2');


Create /app/Http/Middleware/StartSessionMiddleware.php

<?php
namespace App\Http\Middleware;

use Closure;
use Config;

use Illuminate\Session\Middleware\StartSession as BaseStartSession;

class StartSessionMiddleware extends BaseStartSession
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {

        if($request->is('url1') || $request->is('url2')) {
            Config::set('session.driver', 'array');
        }

        return parent::handle($request, $next);
    }
}

Register that by appending a line into /app/Http/Kernel.php

\App\Http\Middleware\StartSessionMiddleware::class,

and now, that laravel_session should not be there anymore for those 2 routes.

I hope this can help someone.

Use

if($request->path('url1') || $request->path('url2')) {

to look for a url path. For EU Cookie tracking I used:

<?php
  namespace App\Http\Middleware;

  use Closure;
  use Config;

  use Illuminate\Session\Middleware\StartSession as BaseStartSession;

  class StartSessionMiddleware extends BaseStartSession
  {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next) {

    if(!isset($_COOKIE['my-cookie'])) {
        Config::set('session.driver', 'array');
    }

    return parent::handle($request, $next);
  }
}

with my-cookie as the name of the cookie you are setting when user accepts.

Related