Posted by

How to enable session in lumen 5.4

You can just use the laravel but you choose lumen simply because the app you're about to build only needs a minimal features but the problem is, the session has been disabled in lumen starting from version 5.2 onwards. Now here's how you can enable it again. 

Step 1

Create a folder/directory in lumen named config and create a php file inside it named session.php and put these codes in it.

<?php

use Illuminate\Support\Str;

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => env('SESSION_LIFETIME', 120),
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => env('SESSION_CONNECTION', null),
    'table' => 'sessions',
    'store' => env('SESSION_STORE', null),
    'lottery' => [2, 100],
    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE'),
    'http_only' => true,
    'same_site' => 'lax',
];

Step 2:

Load the created file session in lumen by updating the file bootstrap/app.php, add this line of code next to CorsMiddleware.

$app->configure('session');

Bind the session manager

$app->bind(Illuminate\Session\SessionManager::class, function ($app) {    
    return $app->make('session');
});

Add the start session middleware

$app->middleware([
    'Illuminate\Session\Middleware\StartSession'
]);
This is how it looks on my end

Step 3:

Create the folder that will be used as storage.

storage/framework/sessions

Step 4:

Last was to update the environment file (.env). Change the value of SESSION_DRIVER=file or add it if it doesn't exists.


Step 5: How to use it

From your controller just import it 

use Illuminate\Http\Request;

And just call it in the method like this.

public function yourMethod(Request $request) {
    $session = $request->session();
    $session->put('sample','hello');
    echo $session->get('sample');  // return hello
}

Hope that helps!