I'm using Laravel 8 and am having trouble with redirecting the user when they are not logged in. I have found several similar questions but they are all in older versions of laravel and none of their solutions work.
I believe I am supposed to use Route::group() to apply the redirect to all my routes. It currently looks like this:
// In web.php
Route::group(, function(){
Route::get('/', [HomeController::class, 'home'])->name('home');
Route::get('/account', [HomeController::class, 'account'])->name('account');
Route::get('/feedback', [HomeController::class, 'feedback'])->name('feedback');
Route::get('/help', [HomeController::class, 'help'])->name('help');
});
I'm not sure what I'm supposed to be using in my first parameter in the group function. I believe that I need it to look through either the session or a cookie to see if there is a logged user?
At the moment, a user is stopped from logging in if they are on the login page and type the wrong user/password so the authentication is working. However, if they manually type a url in, ex. ip:port/help, they will be allowed access.
I want to have all routes on the site redirect to the login page unless the user is authenticated.
My Authentication code looks like this in my LoginController.php:
public function doLogin(Request $request){
DB::connection('mysql');
$args = $request->except('_token');
// attempt to do the login
if (Auth::attempt($args)) {
// validation successful!
return redirect('home');
} else {
// validation not successful, send back to form
return redirect('login');
}
}
My route to get to the doLogin function which is called from an html form action looks like:
Route::post('authenticate', [LoginController::class, 'doLogin'])->middleware('web');
If anyone could give any solutions or lead me on the right path, that'd be amazing. Thanks!
Edit: Solution!
In the parameter I was questioning about I needed to simply add the auth middleware.Route::group(['middleware' => 'auth'], function(){
Route::get('/', [HomeController::class, 'home'])->name('home');
Route::get('/account', [HomeController::class, 'account'])->name('account');
Route::get('/feedback', [HomeController::class, 'feedback'])->name('feedback');
Route::get('/help', [HomeController::class, 'help'])->name('help');
});