Laravel 8: how to customize Fortify redirect according to user role
Let’s take as a case study a site which allows you to put people (which we will define as private from here on) in contact with a possible professional (which we will define as company).
This role will be managed in the registration phase: our goal is to redirect individuals to an estimate request page and to redirect companies on a page dedicated to their profile (job sector, hourly and geographical availability and so on).
We therefore start with the assumption that we will have a column called role in the users table, where in the registration phase we will indicate whether the user is private or company.
Using Laravel Fortify, we know that we can manage the post login and register redirect through the constant HOME indicated in App\Providers\RouteServiceProvider.php, but it will be identical for both actions.
We need to broaden the process.
We know that Laravel Fortify manages in a hidden way the greates part of its functions. Digging deeper, reaching vendor/fortify/src/Http/Responses, we could find a file called RegisterResponse.php.
It’s this we need to override, as inside the toResponse() function he does nothing but follow the redirect indications established by the register route (i.e. the value of the HOME constant).
But how we do it?
Within our project, in the App\Http folder we need to create a new folder called Responses with a file inside it called RegisterResponse.php, in which we will paste the same code found in the original one.
Now, let’s change the content of the toResponse() function:
But what are we doing?
We are managing the value of a variable called $home through a ternary operator: if the registering user role is company, then the value of $home will be the URI (or the route() function) that takes me to the company profile; otherwise, and therefore the user will be of role private, the value will become the URI that leads me to request an estimate.
This function will therefore have to return a redirect of $home.
However, we have not finished in this file yet, as we need to update the namespace and the classes used:
What have we done?
We updated the namespace, as our working environment was no longer the Fortify folder inside vendor but we are in App\Http\Responses now; we then imported the Auth class, to manage the user; the last line remains identical, as this class uses a specific interface.
But we need some other few steps.
In App\Providers\FortifyServiceProvider.php we need to add:
We use the singleton() function to allow us to exploit through Dependency Injection not only a class (RegisterResponse) but also an interface (RegisterResponseContract).
The same concepts can also be used to manage the login response.
And now we are ready to go!