Laravel session data is lost after click

陌路散爱 提交于 2021-02-08 07:56:38

问题


class FileController extends Controller
{
    public function login()
    {
        /*
         * TODO: Handle via CAS
         * Hardcoded for demo purposes
         */
        Session::put('isLogged', true);
        Session::put('index', "123456");

        return View::make('login');
    }

    public function user()
    {
        if(Session::get('isLogged') == true )
            return View::make('user');
    }
}

I have the following code. There is a link on login that goes to the FileControllers@user . On the second page my session data is lost (Session::all() is empty). What could be causing this issue?


回答1:


Try wrapping your routes (inside app/Http/routes.php) in a Route::group() with the web middleware:

Route::group(['middleware' => ['web']], function () {
    // My Routes
});

An easy way to test this:

Route::group(['middleware' => 'web'], function () {
    Route::get('', function () {
        Session::set('test', 'testing');
    });

    Route::get('other', function () {
        dd(Session::get('test'));
    });
});

If you remove the web middleware, you'll receive null since the web middleware is responsible for starting the session.

Ensure you have the web middleware group inside your app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        Middleware\VerifyCsrfToken::class,
    ],
];


来源:https://stackoverflow.com/questions/35139990/laravel-session-data-is-lost-after-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!