Redirect user dynamically to the right path in laravel

Redirect user dynamically to the right path in laravel

Imagine you have multiple type of users and you want to redirect each one them to the right path after they’ve verified their email address.

Logic

  1. User register
  2. User receive verification email
  3. User verified
  4. Redirect to path

Step One send verification email:

All you have to do is to set your user model like this:

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;
    //…
}

Step Two redirect user:

Open VerificationController controller from App\Http\Controllers\Auth and add following function:

protected function verified(Request $request)
{   
    $user = User::find($request->route('id'));

    if ($user->store == true) {
        return redirect()->route('store-owners');
    } else {
        return redirect()->route('panel');
    }
}

Break it down

- We’ve added store column to our users table (You can add any column based on your requirements).

- Then in verification controller we’ve added verified function which is reserved by laravel for us for exact same purpose.

- In verified function we add if statement to check if our user is store owner or not and redirect them to related path.

Note1: You can extend your if statement based on your columns and variables and add more routes.

Note2: This only works for after users verified their email address, if you wish to redirect them after each time login you need to add similar function to your LoginController as well.

- Last updated 7 months ago

Be the first to leave a comment.

You must login to leave a comment