Citrus
Citrus

Reputation: 78

Laravel 5.2 session not persisting

Lately I've been working on a project in Laravel 5.2 and now I'm having problems with sessions not persisting. I've read most of the questions already asked regarding this but everyone has the same answer that I have already tried - applying web middleware.

I've read that there was a new L5.2 update where the web middleware group is already applied by default. I checked my routes with php artisan route:list and I can see that every route has only 1 web middleware applied.

I'm creating session with $request->session()->put('key', 'value') but as soon as I comment that line the session is nowhere to be seen anymore.

Edit

I want to set the session inside a controller when I visit a news page, but I tried it on a simple test route as well. Route where I set this is news/{id} and I want to use it on the front page which is in /

I wish to store recently visited pages in session so I can then show it to the user on the front page.

Session config file I left untouched. So it's using file driver

Upvotes: 0

Views: 354

Answers (1)

Fadi Botros
Fadi Botros

Reputation: 111

Here is a tested routes to use for your projects Please use a middleware instead of the function in the routes file

routes.php

// Only as a demo
// Use a middleware instead

function addToSession ($routeName) {
    $visited = session()->get('visited', []);
    array_push($visited, $routeName);
    session()->put('visited', $visited);
}

Route::get('/', function () {
    addToSession('/');
    return view('welcome');
});

Route::get('/second', function () {
    addToSession('/second');
    return view('welcome');
});

Route::get('/third', function () {
    addToSession('/third');
    return view('welcome');
});

Route::get('/history', function() {
    return session()->get('visited');
});

The /history route will return a JSON having the history.

Upvotes: 1

Related Questions