0
votes

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

1
Please provide more code. Show us where you set it, show us where you request it. Tell us more about your session driver and what you want to achieve in total - Frnak

1 Answers

1
votes

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.