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
instead of doing this in your AppServiceProvider
since Service Providers are initialized before the session, do the same thing on your LanguageManager middleware
Place
AppHttpMiddlewareLanguageManager::class,
before theverifytoken
. Order is requiredSecond, set delay in the view load.
In AppServiceProvider