Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RedirectIfAuthenticated redirect if attempt to open other login form

I have two login forms with two different tables.One is default with /login route and the other has route /myportal. I have extra logincontroller

    protected $redirectTo = '/student-home';
    public function showLoginForm()
    {
        return view('my_portal');
    }

    public function logout(Request $request)
    {
        $this->guard()->logout();
        $request->session()->flush();
        $request->session()->regenerate();
        return redirect('/my_portal');
    }

    protected function guard()
    {
        return Auth::guard('web_student');
    }

    public function username () 
    {
        return 'username';
    }

This login is working fine. But, I am having problem with RedirectIfAuthenticated

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect('/home');
        }

        else if(Auth::guard('web_student')->check())
        {
            return redirect('student-home');
        }
        return $next($request);
    }

Now, if the user is already logged in, it is redirected to /student-home only if the route is /login and not /my-portal. i.e only if i click on regular form not this extra form I created. How can I redirect to student-home if user clicked on /my-portal?

like image 764
Steve Avatar asked Oct 27 '17 02:10

Steve


2 Answers

You can connect a controller to the my-portal route with :

Route::get('test', 'exampleController@example') ;

Then in the controller function, you can check if the user is already logged in by

public function example() {
    if(Auth::check()) {
        //This condition will run if the user is logged in !
        return redirect('student-home');
    }
    //Do whatever you want if user is not logged in!
}

Hopefully, this answers your question!

like image 156
Nisarg Shah Avatar answered Oct 20 '22 06:10

Nisarg Shah


Please change your RedirectIfAuthenticated middleware like this

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {

           if(guard == 'web_student') {
                return redirect('student-home');
             }else return redirect('/home');
        }
    return $next($request);
}

The problem with your code is that the following segment will always true if a user is logged in. You have to check for whether or not a specific guard is set, inside this if statement if you want to redirect them accordingly.

if (Auth::guard($guard)->check()) { return redirect('/home'); }

like image 2
HasilT Avatar answered Oct 20 '22 07:10

HasilT