DEV Community

Koussay
Koussay

Posted on • Edited on

4

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
youngswagx profile image
Sammy

on this topic where will i create the LoginResponse file?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay