Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gayathri's avatar

How to set a session variable

In session.php file, I am using driver='database' and table='sessions' now I am struck with how to set a session for a variable.

Native sessions, ie. $_SESSION is supported by Laravel 5 ?

0 likes
13 replies
bobbybouwmann's avatar

Settings sessions

session(['key' => 'value']);
// Or
session()->put('key', 'value')

Getting a value from a session

$value = session()->get('key');
// Alternatively you can pass in a default value
$value = session()->get('key', 'default);

Deleting a session

session()->forget('key');

Source: http://laravel.com/docs/5.1/session#basic-usage

5 likes
bestmomo's avatar

For lazy man like me :

$value = session('key');
gayathri's avatar

Showing a error - Undefined variable Session::put()

1 like
bobbybouwmann's avatar

Import the session facade or use the syntax helmerdavila showed you

bobbybouwmann's avatar
use Session;

class SomeClass {
    Session::put('key', 'value', 'minutes');
}
2 likes
Jhourlad's avatar

There should be a way to access the native $_SESSION specially if you are sharing session with other applications that do not ship as Composer package or otherwise have no Facade support.

Anybody?

DarkSpirit's avatar

@bobbybouwmann What does the minutes do in Session::put('key', 'value', 'minutes')? I can't find anything about the third argument on Laravel documentation.

bobbybouwmann's avatar

@DarkSpirit You can set the amount of the minutes the item needs to be cached

The minutes are optional, but you can set them in when you call put on the cache facade.

// Illuminate/Cache/Repository.php

/**
 * Store an item in the cache.
 *
 * @param  string  $key
 * @param  mixed   $value
 * @param  \DateTime|int  $minutes
 * @return void
 */
public function put($key, $value, $minutes = null)

And for the documentation: https://laravel.com/docs/5.2/cache#storing-items-in-the-cache

1 like
ArchanaKumari's avatar

Can anyone say me where to write the session code? session(['key' => 'value']); please show me the full code.

huytran's avatar

In your controller or anywhere you want to store a session. You can also retrieve session's data in your blade by using session('key').

Hope this helps !

mohasin-dev's avatar

Put a value in session

session()->put('key', 'value');

Example:

session()->put('email', '[email protected]');

Get a value from session

$value = session()->get('key');

Example:

$email = session()->get('email');
1 like

Please or to participate in this conversation.