skip to Main Content

I want to access sessions in the AppServiceProvider file in Laravel. To achieve this, I’ve created a middleware file and defined it in the kernel.php file. However, even after doing this, when I use the Log function in the AppServiceProvider file, the session value appears to be empty every time. I’m sharing my files and code below. Is there anyone who can assist me with this?
I’ve defined my LanguageManager file in the Kernel.php before and after StartSession as I read that this might help in a certain article. However, despite doing so, there hasn’t been any change. I’m still seeing an empty value in my Log file.

Middleware/LanguageManager.php

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesApp;
use SymfonyComponentHttpFoundationResponse;

class LanguageManager
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }

        return $next($request);
    }
}

Kernel.php

    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareLanguageManager::class,
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            // LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            IlluminateRoutingMiddlewareThrottleRequests::class.':api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

AppServiceProvider

        $lang=session()->get('locale');
        Log::info($lang);
        if (!(session()->get('locale')) ) {
            session()->put('locale', env('APP_DEFUALT_LANG'));
        }

ChangeLang function for change to locale value

    public function changeLang(Request $request){
        session(['locale' => $request->lang]);
        return response()->json(['message'=>"Language changed succesfully"], 200);
    }

My code keeps entering the if statement in the AppServiceProvider, where it assigns the default value to the locale value. Because of this, I’m unable to send the updated value through the provider. What should I do?

2

Answers


  1. instead of doing this in your AppServiceProvider

    $lang = session()->get('locale');
    Log::info($lang);
    
    if (!(session()->get('locale')) ) {
        session()->put('locale', env('APP_DEFUALT_LANG'));
    }
    

    since Service Providers are initialized before the session, do the same thing on your LanguageManager middleware

    public function handle($request, Closure $next)
    {
        App::setLocale(session()->get('locale', env('APP_DEFUALT_LANG')));
    
        return $next($request);
    }
    
    Login or Signup to reply.
  2. Place AppHttpMiddlewareLanguageManager::class, before the verifytoken. Order is required

    'web' => [
        AppHttpMiddlewareEncryptCookies::class,
        .... 
        IlluminateViewMiddlewareShareErrorsFromSession::class,
        AppHttpMiddlewareLanguageManager::class,  // <-- Move it here
        AppHttpMiddlewareVerifyCsrfToken::class,
        IlluminateRoutingMiddlewareSubstituteBindings::class,
    ],
    

    Second, set delay in the view load.

    In AppServiceProvider

    public function boot()
    {
        View::composer('*', function ($view) {
            $lang = session()->get('locale');
    
            Log::info($lang);
    
            if (!session()->get('locale')) {
                session()->put('locale', env('APP_DEFUALT_LANG'));
            }
          
            $view->with('lang', $lang);
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search