Set session variable in laravel
Asked Answered
I

10

53

I would like to set a variable in the session using laravel this way

Session::set('variableName')=$value;

but the problem is that I don't know where to put this code, 'cause I would like to set it for one time (when the guest visite the home page or any other page)? The main idea is to use a global variable to use it in all application controllers, I heared about something related to configuration variables but I'm not sure if it will be a good Idea to use config variables or only the session? Thanks

Instability answered 9/2, 2015 at 19:33 Comment(2)
that is illegal PHP. the left-hand-side of an assignment operation cannot be an expression. set() is a function/method call - it can only RETURN a value, you cannot assign a value to it.Stitch
This is very well documented here: laravel.com/docs/5.0/sessionStricker
U
124

The correct syntax for this is:

Session::set('variableName', $value);

For Laravel 5.4 and later, the correct method to use is put:

Session::put('variableName', $value);

To get the variable, you would use:

Session::get('variableName');

If you need to set it once, I'd figure out when exactly you want it set and use Events to do it.

For example, if you want to set it when someone logs in, you'd use:

Event::listen('auth.login', function() {
    Session::set('variableName', $value);
});
Unspent answered 9/2, 2015 at 19:45 Comment(4)
Please Tell Me Where We Can Use this Event?Stiletto
in routes or controller?Stiletto
You'd probably want to create a service provider for it and put it in there.Unspent
@user3158900, why there is a need of service provider?Anchusin
P
32

I think your question ultimately can be boiled down to this:

Where can I set a long-lived value that is accessible globally in my application?

The obvious answer is that it depends. What it depends on are a couple of factors:

  • Will the value ever be different, or is it going to be the same for everybody?
  • How long exactly is long-lived? (Forever? A Day? One browsing 'session'?)

Config

If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config, e.g. app/config/companyname.php:

<?php
return [
    'somevalue' => 10,
];

You could access this value from anywhere in your application via Config::get('companyname.somevalue')

Session

If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session. This is what you allude to in your question, but you are using incorrect syntax. The correct syntax to store a variable in Session is:

Session::put('somekey', 'somevalue');

The correct syntax to retrieve it back out later is:

Session::get('somekey');

As far as when to perform these operations, that's a little up to you. I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5. Below is an example of using a route filter that leverages another class to actually come up with the value:

// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
    public function makeValue()
    {
        return 42;
    }
}

// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
    $valueMaker = app()->make('ValueMaker');
    Session::put('somevalue', $valueMaker->makeValue());
});

// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
   // Value has already been 'made' by this point. 
   return View::make('view')
       ->with('value', Session::get('somevalue'))
   ;
});
Pepsinate answered 9/2, 2015 at 19:59 Comment(1)
upvote because of hhtg :-) and the good and comprehensive answer.Enticement
V
14

In Laravel 5.6, you will need to set it as:

session(['variableName' => $value]);

To retrieve it, is as simple as:

$variableName = session('variableName');
Vogele answered 13/3, 2018 at 10:56 Comment(2)
Can I retrieve it from any controller ?Rightwards
yes, A session is a way to store information (in variables) to be used across multiple pagesVogele
S
12

For example, To store data in the session, you will typically use the putmethod or the session helper:

// Via a request instance...
$request->session()->put('key', 'value');

or

// Via the global helper...
session(['key' => 'value']);

for retrieving an item from the session, you can use get :

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

or global session helper :

$value = session('key', 'default value');

To determine if an item is present in the session, you may use the has method:

if ($request->session()->has('users')) {
//
}
Suzannasuzanne answered 29/5, 2018 at 20:10 Comment(0)
W
7

To add to the above answers, ensure you define your function like this:

public function functionName(Request $request)  {
       //
}

Note the "(Request $request)", now set a session like this:

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

And retrieve the session in this way:

$data = $request->session()->get('key');

To erase the session try this:

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

or

$request->session()->flush();
Woolworth answered 15/11, 2018 at 23:23 Comment(0)
J
6

in Laravel 5.4

use this method:

Session::put('variableName', $value);
Jockey answered 16/3, 2017 at 19:14 Comment(0)
C
5

In Laravel 6.x

// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session

Cyn answered 11/12, 2019 at 21:56 Comment(0)
G
4

You can try

 Session::put('variable_Name', "Your Data Save Successfully !");  
 Session::get('variable_Name');
Gladine answered 29/5, 2018 at 19:52 Comment(1)
This is used to store value in session \Session::put('variable_Name', "Your Data Save Successfully !"); and this is used Session::get('variable_Name'); to get the value which i store in sessionGladine
V
1

to set session you can try this:

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

also to get session data you can try this:

$request->session()->get('key');

If you want to get all session data:

$request->session()->all();
Valleau answered 11/2, 2020 at 12:46 Comment(0)
I
1

If you want persistence sessions,

Method 1: use session()->save() or Session::save()

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

//then
session()->save();

echo session('key');

Method 2: Move bellow line from protected $middlewareGroups of app\Http\Kernel.php to protected $middleware array as first line

\Illuminate\Session\Middleware\StartSession::class,

Make sure the storage directory has write permission

chmod -R a+rw storage/

Don't use dd() to verify session, use print_r()

Inverse answered 4/4, 2021 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.