Search code examples
phplaravelauthenticationcontrollerlogic

Shorten the Controller Logic Laravel


I'm trying using Laravel login authentication using different guards but I found that there is some repetition within the store method in the Login Controller (the only difference is the guard used, all other logic are the same). I just can't find a way to shorten them into some other logic such as method(function) which can be reusable. So if there is possible way, Please help me out.

 public function store(Request $request)
{

    $request->validate([
        'username' => 'required',
        'password' => 'required'
    ]);


    if (Auth::guard('instructor')->attempt(['email' => $request->username, 'password' => $request->password])) {

        if (auth('instructor')->user()->status === Instructor::HAS_DEACTIVATED) {
            $request->session()->flush();
            Auth::guard('instructor')->logout();
            return redirect('login')->with(
                'error',
                'Your Account has being deactivated . Please Contact your Administrator!');
        }

        return redirect(route('instructor.dashboard'));


    }
    if (Auth::guard('student')->attempt(['email' => $request->username, 'password' => $request->password])) {

        if (auth('student')->user()->status === Student::HAS_DEACTIVATED) {
            $request->session()->flush();
            Auth::guard('student')->logout();
            return redirect('login')->with(
                'error',
                'Your Account has being deactivated . Please Contact your Administrator!');
        }
        return redirect(route('student.dashboard'));
    }
    return back()->with('error', 'Credentials provided do not match any record.');

}


Solution

  • You can create a separate function and then call that function.

        public static function deleteSession($gaurd)
        {
                    $request->session()->flush();
                    Auth::guard($gaurd)->logout();
                    return redirect('login')->with(
                        'error',
                        'Your Account has being deactivated . Please Contact your Administrator!');
    
        }
    

    Then in your store function call deleteSession statically.

         if (auth('instructor')->user()->status === Instructor::HAS_DEACTIVATED)
         {
            self::deleteSession('instructor'); //change gaurd according to your need
         }