I am trying to understand how sessions work in Laravel 5(.4). In one hand there are two ways of using them as described in the official documentation:
There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance.
$request->session()->put('key', 'value');
and
session(['key' => 'value']);
The documentation says:
There is little practical difference between using the session via an HTTP request instance versus using the global session helper.
But it is never explained what the difference is.
In the other hand there is the "Facade way":
Session::put('key', 'value');
And recently I found this Stack Overflow question How to use session in laravel 5.2 controller. train_fox pointed out this way:
session()->put('key', 'value');
So that makes a total of four ways. And I cannot figure out why or when use one or another. Does someone know the difference between those four?
By the way, the only way I could get sessions to work with Redis was with the two last ways.
Thank you in advance for your enlightenment.
Let's consider Facade first:
This facades calls
Illuminate\Session\Store::put()
.Now let's consider the function
session()
:Reading this, we can assume that
session(['a' => 'b'])
works similar thatsession()->put('a', 'b')
(because if it's an array, it callsput
on the same function).app('session')
returnsIlluminate\Session\SessionManager
(https://laravel.com/docs/5.4/facades#facade-class-reference).Illuminate\Session\SessionManager
has a__call
function which in short calls the driver of the session. So it's the same behavior.Now the difference may be in the
$request
function vs all other ones (as it's written in docs). According to the source code it returns a\Symfony\Component\HttpFoundation\Session\SessionInterface
. TheSessionInterface
has not the same methods asIlluminate\Session\Store
so maybe it's why it differs.Ok I give up. It's hard to understand. I can't help you more, I'm lost. I keep this post for history need.