omitobi
omitobi

Reputation: 7334

What is the real difference between Laravel's session() and request()->session()?

I am working on a Laravel(5.2) project that heavily relies on session, quite new though but I was just curious what difference global session() and Http request()->session() has apart from the fact that they have different means of accessing and writing into session?

Here are the few information I have about this from laravel 5.4 doc,

enter image description here

Unfortunately, this does not really make me understand the difference. I have as well googled and stackoverflowed perhaps I could find an answer to no avail. Example is laravel difference of session::flash and request->session->flash but I am not so comfortable with the answer

What is the real difference they have in managing session data? I wouldn't mind a reference to a documentation where this is or even if I have to dig into laravel core.

Thanks

Upvotes: 15

Views: 6715

Answers (3)

DAVID AJAYI
DAVID AJAYI

Reputation: 2154

Unfortunately the best answer has already been given by the Laravel note; and I can only attest to that for now cos I have noticed such situation once.

I couldn't understand why global session('key') refuse to echo the value of $request->session()->put('key', 'value') within the same method. Hopefully I'd come across the situation again just for proof but the last response I'd want to give you is:

"There are no differences, it's just a shortcut."

Cos just like the docs mentioned, there's difference notable in practice

Upvotes: 0

Ahmad
Ahmad

Reputation: 455

i think this would help you: $request->session() and session() both are same thing.

There are two primary ways of working with session data in Laravel: the global function in session() helper and via a $request instance.

you can use it like this

public function testMyMethod(Request $request){

    //$userExist = $request->session()->exists('user_id');
    $userExist = $request->session()->has('user_id');

}

Upvotes: 0

thchp
thchp

Reputation: 2404

session() is a helper that gives you a faster access to request()->session()

Note that request() is also a helper that gives you a faster access to the request object.

There are no differences, it's just a shortcut.

Upvotes: 16

Related Questions