DEV Community

Koussay
Koussay

Posted on • Updated on

Redirect User based on condition in Laravel Fortify

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.

After creating the class, all you need to do now, is to bind the newly creating class to Fortify.

All you need to do is open FortifyServiceProvider.php, and in the boot method, add this code

        $this->app->singleton(\Laravel\Fortify\Contracts\LoginResponse::class, LoginResponse::class);

Enter fullscreen mode Exit fullscreen mode

And that's it ♥

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.

Top comments (1)

Collapse
 
youngswagx profile image
Sammy

on this topic where will i create the LoginResponse file?