Home > Enterprise >  Not able to access session data inside web.php
Not able to access session data inside web.php

Time:12-21

I want to use session variable in my web.php file. As I want to create dynamic route according to current_index from session. And current_index is changed as per different login.

$index = Session::get('current_index');


Route::prefix($index)->group(function () {
            Route::get('index', [SystemConfigController::class, 'index'])->name('systemConfig.index');
            Route::post('list', [SystemConfigController::class, 'index'])->name('systemConfig.list');
            Route::post('testmail', [SystemConfigController::class, 'testMail'])->name('systemConfig.testmail');
            Route::post('edittable', [SystemConfigController::class, 'editTable'])->name('systemConfig.edittable');
        });

Can you please help me to figure out this issue?

CodePudding user response:

Load session before initiating routes

protected $middlewareGroups = [
    'web' => [
        \Illuminate\Session\Middleware\StartSession::class, 
    ],
];

CodePudding user response:

RouteServiceProvider are booted before the StartSession middleware, so you cannot access session in route files. Use middleware to check instead

Route::middleware('session.has.index')->prefix($index)->group(function () {
   Route::get('index', [SystemConfigController::class, 'index'])->name('systemConfig.index');
   Route::post('list', [SystemConfigController::class, 'index'])->name('systemConfig.list');
   Route::post('testmail', [SystemConfigController::class, 'testMail'])->name('systemConfig.testmail');
   Route::post('edittable', [SystemConfigController::class, 'editTable'])->name('systemConfig.edittable');
});

create middleware

php artisan make:middleware SessionHasIndex

Update middlewares to check the session, if it does not have corresponding session, abort the request:

app/Http/Middleware/SessionHasIndex.php

public function handle($request, Closure $next) 
{ 
    $request->route()->prefix(Session::get('index')); 
    return $next($request); 
} 

Install Middlewares, so routing can use the middlewares

app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        ...
        'session.has.index' => , \App\Http\Middleware\SessionHasIndex::class       
        ...
    ],
  • Related