Session not working in middleware Laravel 5

后端 未结 6 1285
广开言路
广开言路 2020-12-20 13:58

Im trying to work with Sessions in Laravel 5 Middleware, but they are not working. To be specific - var_dump(Session::all()); at the start of handle method give

6条回答
  •  鱼传尺愫
    2020-12-20 14:35

    I had the same problem, I was using Sessions to store the locale at login, then redirect to the main dashboard, but when the middleware loads, the session is not initiated yet. So it wouldn't work.

    Let me say first, I'm no Laravel expert, but this way works in Laravel 5.3:

    1) php artisan make:middleware SetApplicationLanguage

    2) Add this to app/Http/Kernel.php $middlewareGroup variable:

    \Illuminate\Session\Middleware\StartSession::class,
    \App\Http\Middleware\SetApplicationLanguage::class,
    

    Notice that this new Middleware comes AFTER the StartSession class.

    3) This is my app/Http/MiddleWare/SetApplicationLanguage.php:

    namespace App\Http\Middleware;
    
    use App;
    use Closure;
    use Illuminate\Support\Facades\Auth;
    
    class SetApplicationLanguage
    {
    
        /**
         * Handle an incoming request.
         *
         * @param \Illuminate\Http\Request $request            
         * @param \Closure $next            
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if (isset(Auth::user()->locale)) {
                App::setLocale(Auth::user()->locale);
            }
    
            return $next($request);
        }
    }
    

    Notice that I don't use Session in it this example. That's because when I add my Middleware AFTER the StartSession class, session would work, but Auth::user() would be available again, so I could just use Auth::user()->locale and no need for Sessions at all.

    But you could do it, just use App::setLocale(Session::get('locale')) instead and of cause include the Session facade.

提交回复
热议问题