skip to Main Content

In my Laravel Project i have few routes which i want to protect if the user is not authenticated thats why i make this changes to Authenticate middleware :

namespace AppHttpMiddleware;

use IlluminateAuthMiddlewareAuthenticate as Middleware;
use IlluminateHttpRequest;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }
} 

I am handling my login register in the AuthController like this :

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesValidator;
use IlluminateSupportFacadesAuth;

class AuthController extends Controller
{
    public function login_view(){
        return view('auth.Login');
    }
    public function login(Request $request){
        $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);
    
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return redirect()->back()->with('error', 'User with this email does not exist');
        }

        try {
            if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
                $user = Auth::user();
                session()->put('user_id', $user->user_id);
                session()->put('type', $user->type);
                // dd(Auth::user());
                if ($user->type == 'User') {
                    return redirect('Home');
                } else {
                    return redirect('Dashboard');
                }
            } else {
                // return redirect()->back()->with('error', 'Wrong Password');
                dd($e->getMessage());
            }
        } catch (Exception $e) {
            // return redirect()->back()->with('error', $e->getMessage());
            dd($e->getMessage());
        }
    }

    public function register_view(){
        return view('auth.Register');
    }
    public function register(Request $request){
        $validator = Validator::make($request->all(), [
            "society_no" => "required",
            "rooms" => "required",
            "firstname" => "required",
            "lastname" => "required",
            "email" => "required|email|unique:USERS",
            "password" => "required|min:8",
            "cpassword" => "required|same:password",
        ], [
            "password.min" => "The password must be at least 8 characters long.",
            "cpassword.same" => "The password and confirm password must match.",
            "email.unique" => "This email is already registered."
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        try {
            $newUser = new User();

            $newUser->society_no = $request->input('society_no');
            $newUser->rooms = json_encode($request->input('rooms'));
            $newUser->firstname = $request->input('firstname');
            $newUser->lastname = $request->input('lastname');
            $newUser->email = $request->input('email');
            $newUser->password = Hash::make($request->input('password'));

            if ($newUser->save()) {
                return redirect('login')->with('success', 'User Registered Successfully');
            }
        } catch (Exception $e) {
            // dd($e->getMessage());
            return redirect()->back()->with('error', 'Failed to Register User');
        }
    }
    
    public function forgot_view(){
        return view('auth.Forgot');
    }
    public function forgot(Request $request){
        dd($request->all());
    }

    public function logout_view(){
        return view('auth.Logout');
    }
    public function logout(){
        session()->forget('user_id');
        session()->forget('type');
        Auth::logout();
        return redirect('login');
    }
}

This is where i apply the auth middlware in my web.php :

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersAuthController;

Route::group(['middleware' => 'auth'],function () {
    Route::get('/Home', function () {
        return view('Home');
    })->name('Home');
    Route::get('/Profile', function () {
        return view('Profile');
    })->name('Profile');

    Route::get('/Logout', [AuthController::class, 'logout_view'])->name('Logout');
    Route::post('/Logout', [AuthController::class, 'logout'])->name('Logout');
});

    Route::get('/login', [AuthController::class, 'login_view'])->name('login');
    Route::post('/login', [AuthController::class, 'login'])->name('login');
    
    Route::get('/Register', [AuthController::class, 'register_view'])->name('Register');
    Route::post('/Register', [AuthController::class, 'register'])->name('Register');
    
    Route::get('/Forgot', [AuthController::class, 'forgot_view'])->name('Forgot');
    Route::post('/Forgot', [AuthController::class, 'forgot'])->name('Forgot');

, and finally this is my Model User.php :

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

use IlluminateFoundationAuthUser as Authenticatable;


// class User extends Model
class User extends Authenticatable
{
    use HasFactory;
    protected $table = 'USERS';
}

After applying the middleware to my routes, the page keeps redirecting back to login even after successful authentication with no errors. After some debugging, I discovered that the Auth::user() is null whenever login finishes, which I don’t understand because, as you can see in my login function, when login is successful, the user gets succesfully redirected to Home or Dashboard with the help of $user = Auth::user(); $user->type == ‘User’ IF THE MIDDLEWARE IS NOT SET.

2

Answers


  1. I think there may be some cache issue. Your code is working fine in my system. Try by running php artisan cache:clear

    Login or Signup to reply.
  2. try changing your route name from Home to home. and after this run php artisan optimize and then serve. As laravel by default redirects to route name ‘home’ which you can change in RedirectIfAuthenticated if you want to keep your home route as Home

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search