I have 2 Blade files: login.blade.php and dashboard.blade.php. In LoginController, I am using Auth::attempt() to authenticate the user and redirect to the dashboard if successful.
For the Dashboard, I have one more middleware to check the login status. After I successfully logged in and navigated to the dashboard, it took me back to the login page. That means the login status is false.
In the login function. If I try return Auth::user() right after using attempt it works. But when checking in middleware or another route, Auth::check() returns false.
web.php
Route::group(['namespace' => 'App\Http\Controllers'], function () {
Route::get('login', 'PublicController@index')->name('login');
Route::post('login', 'PublicController@login')->name('login.post');
});
Route::group(['namespace' => 'App\Http\Controllers', 'middleware' => ['auth.login']],
function () {
Route::get('/', 'AdminController@index')->name('dashboard.index');
});
controller
public function login(Request $request) {
$data = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if(Auth::attempt($data)) {
$request->session()->regenerate();
if(!$request->login_as || Auth::user()->role != $request->login_as) {
return back()->withErrors(['message' => 'False!'])->withInput();
}
return redirect()->intended(route('dashboard.index'));
}
return back()->withErrors(['message' => 'False!'])->withInput();
}
AuthCheck.php middleware - I have added this middleware to $middlewareAliases
class AuthCheck
{
public function handle(Request $request, Closure $next)
{
if(!Auth::check()) {
return redirect('login');
}
return $next($request);
}
}
auth.php config and session config
//Auth config
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Account::class,
]
]
//Session config
{
"driver": "file",
"lifetime": "120",
"expire_on_close": false,
"encrypt": false,
"files": "/Users/chanhhuynh/Documents/Freelance/rental-
management/storage/framework/sessions",
"connection": null,
"table": "sessions",
"store": null,
"lottery": [
2,
100
],
"cookie": "laravel_session",
"path": "/",
"domain": null,
"secure": null,
"http_only": true,
"same_site": "lax"
}
I have searched and tried some way but still not work. Is there any solution to fix it? Thanks