I have a signup route. After it register on step1, it emails to the user to verify his account and have a link on his email. After clicking the link, it should redirect to signup/step2
, and finished and he can access the job-seeker/home
.
so the logic is after finished the registration, user cannot visit again to signup/step2
cause user already finished fill up the form.
and before fillup signup/step2
, he can't access also the job-seeker/home
. So it's vice versa.
basically my middleware was first: check if the user completed the step2 and added true on column is_completed
in database. then on the second middleware is to visit only his route by his role, he can't access other routes from other role and redirect to his home based on his role.
But it throws me too many redirect and switching both side even I still didn't fill up the step2 yet. this is my gif below.
MyCode
Kernel.php
class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
...
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'isCompleted' => \App\Http\Middleware\IsCompleted::class,
];
Middleware/IsCompleted.php
class IsCompleted
{
public function handle($request, Closure $next)
{
if(auth()->user()->isCompleted == 1){
return $next($request);
}
// if 0, redirect to step2
return redirect()->route('register.step2');
}
Middleware/RedirectIfAuthenticated.php
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if ( Auth::user()->hasRole('job-seeker') ) {
return redirect()->route('job-seeker.home');
} else if(Auth::user()->hasRole('admin')) {
return redirect()->route('admin.home');
}
}
return $next($request);
Routes/Web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['verified', 'isCompleted']], function() {
Route::group(['prefix' => 'admin', 'name' => 'admin.'], function() {
Route::get('/home', function(){ return "test"; })->name('admin.home');
});
Route::group(['prefix' => 'job-seeker', 'name' => 'job-seeker.'], function() {
Route::get('/home', 'Jobseeker\HomeController@index')->name('job-seeker.home');
});
});
Auth::routes(['verify' => true, 'register' => false]);
Route::get('signup/{usertype}' , 'Auth\RegisterController@getStep1')->name('register.step1');
Route::post('signup/{usertype}' , 'Auth\RegisterController@postStep1');
Route::group(['middleware' => ['auth']], function() {
Route::get('signup/step2' , 'Auth\RegisterController@getStep2')->name('register.step2');
Route::post('signup/step2' , 'Auth\RegisterController@postStep2');
});
EDIT 1
I inspect the page and go to network tab, and this is the result.