I'm using laravel 12.0.1 and try to check the user is logged in or not in the middleware.
I set the session value in api Controller, but when I call this value in the middleware, it is null.
And my log only shows the token in session.
How to get session value in the middleware?
My laravel_session in header and corresponding session value in database:
laravel_session=fca6d3xPRfTdlHBSTJWBd0KvaieSdKPbcGkFBZxa
a:3:{s:6:"_token";s:40:"0hYLgh1hHAZNW2Ar8E6MDBP5zKJXlLynSjt4dgTp";s:4:"user";s:5:"admin";s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
My log show another session value:
my session value: {"_token":"T9EtbOAiUwUYc9s1l1gC4TrdSkTj8nT9SDFbqTIA"}
I use the session function to set global session value, and I'm sure that name is not null.
// loginVerify
$validate = $request->authenticate();
if ($validate)
{
$post = $request->post()['body'];
$acct = User::where([
[ 'email', '=', $post['acct'] ],
[ 'password', '=', $post['ps'] ],
])->first();
session(['user' => $acct['name']]);
return $acct;
}
// middleware managePage
public function handle(Request $request, Closure $next): Response
{
Log::debug ('my session value: ' . json_encode(session()->all()));
dd($request->header('Cookie'));
if (empty(session('user')))
{
return redirect('/managerLogin');
}
return $next($request);
}
here is my middleware setup:
$middleware->prependToGroup('manageSetting', [
\Illuminate\Session\Middleware\StartSession::class,
]);
$middleware->appendToGroup('managePage', [
ManagerPage::class,
]);
and this is my route setup:
// web route
Route::middleware(['manageSetting', 'managePage'])->group(function ()
{
Route::get('/homeManage', function ()
{
return Inertia::render('manage/homeManage');
});
Route::get('/groupManage', function ()
{
return Inertia::render('manage/groupManage');
});
});
Route::middleware(['manageSetting'])->group(function()
{
Route::get('/managerLogin', function ()
{
return Inertia::render('manage/login');
})->name('managerlogin');
});
//api route
Route::middleware(['manageSetting'])->group(function ()
{
Route::post('/updateGroup', [GroupController::class, 'update']);
Route::post('/updateHome', [KeyVisualController::class, 'update']);
Route::post('/loginVerify', [UserController::class, 'login']);
});
Notes:
- I've tried the reflash and keep functions.
- The save function in request is not yielding working results for me, too.
- When I try to get the session in the manage page Controller API, I get another laravel_session. How to get the same laravel_session in all processes?
- I can get session value in login function with session('user').
StartSessionmiddleware for session handling in API routes. Check this post.StartSessionin themanageSettinggroup and set the login and manage route to use this middleware, but it's still can't get correct value