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?
middlewareGroups from kernel.php file :
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
// IlluminateSessionMiddlewareAuthenticateSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
AppHttpMiddlewareLocalization::class,
],
'api' => [
// LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
'throttle:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
];
Edited below :
I have scenario like this. I have to create dynamic route like below:
$index = Session::get('current_index');
If $index is 0 then my route list is like below :
Route::prefix(0)->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');
});
If $index is 1 then my route list is like below :
Route::prefix(1)->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');
});
2
Answers
Load session before initiating routes
RouteServiceProvider are booted before the StartSession middleware, so you cannot access session in route files. Use middleware to check instead
create middleware
Update middlewares to check the session, if it does not have corresponding session, abort the request:
app/Http/Middleware/SessionHasIndex.php
Install Middlewares, so routing can use the middlewares
app/Http/Kernel.php