Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - session doesn't work

Here's config/session.php:

return [
    'driver' => 'file',
    'files' => storage_path().'/framework/sessions',
];

My storage/framework/sessions have 755 permissions.

When I put these 2 line in my controller

Session::set('aa', 'bb');
dd(Session::get('aa'));

I receive expected "bb" output. But if I comment first line:

// Session::set('aa', 'bb');
dd(Session::get('aa'));

and refresh page, I still expecting "bb" but getting null.

Also, storage/framework/sessions is empty.

What should I do to make Session working?

like image 290
Limon Monte Avatar asked Mar 30 '15 12:03

Limon Monte


People also ask

Why session is not set in laravel?

Solution 01 Session not Working in LaravelBy default, web middleware provides a session start class to store the session state. Try to move your routes into the web middleware like below. }); That's it.

What is session() in Laravel?

Laravel session is a way of storing the user information across the multiple user requests. It keeps track of all the users that visit the application. Let's understand the session through an example. First, we create a form on which we apply the properties of the session.

How do I increase my session lifetime in laravel?

If you want to increase your session life time then we need to change in . env file and it is very easy to change it from configuration file in laravel. laravel provides you session. php file there is we can see 'lifetime' key option for setting time in minutes.


2 Answers

if you're use api route , you might have this problem with your session and most of the time sessions return null , try to use web route for this

like image 183
arash peymanfar Avatar answered Oct 02 '22 15:10

arash peymanfar


Laravel 5 handles sessions via a middleware class called StartSession. More importantly, this middleware is a TerminableMiddleware and the code that actually saves the data (in your case to the session file) is located in the terminate method, which is run at the end of the request lifecycle:

public function terminate($request, $response)
{
    if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions())
    {
        $this->manager->driver()->save();
    }
}

When calling dd(Session::get('aa')); the request is being interrupted before the terminate method of the middleware can be called.

Funnily enough, the Laravel Middleware Documentation actually explains Terminable Middleware logic by giving the Laravel StartSession middleware as an example:

For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser.

That being said, try using var_dump() instead of using dd().

like image 26
Bogdan Avatar answered Oct 02 '22 13:10

Bogdan