DEV Community

loading...

Redirect User based on condition in Laravel Fortify

koossaayy profile image Koussay ・1 min read

3aslema (means Hello in Tunisian)
Recently I had a Laravel project, where I had to redirect users based on their role, to their dashboards.
I'm using Laravel 8, so I thought about using Laravel Fortify.
So after installing and configure it, create a new PHP file, name it, let's say "LoginResponse"
This class will implement the "LoginResponseContract" and it will override the "toResponse" method, and in that method we will implement the logic.
So the class will be like this

use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;

class LoginResponse implements LoginResponseContract
{

    /**
     * toResponse
     *
     * @param mixed $request
     * 
     * @return RedirectResponse
     */
    public function toResponse($request): RedirectResponse
    {
        if(Auth::user()->role === "Admin")
            return redirect()->route('admin');
        return redirect()->route('user');

    }

}

Enter fullscreen mode Exit fullscreen mode

In this example, we will check the role of the authenticated user, if it's admin, we will redirect it the admin route, otherwise, we will redirect it the default route.

P.S : I'm not a Laravel Expert, I'm just writing real-world examples I encounter, so Please correct me if I'm wrong.

Discussion (0)

pic
Editor guide