2

I've followed the instructions here to make a login page. It's working; however I'm having trouble making the redirect dynamic. What I mean is that, I want to redirect the user to different URLs, based on their role (custom models that I've already defined).

Here's my AuthController (I've removed boilerplate):

 use AuthenticatesAndRegistersUsers, ThrottlesLogins;
 private $redirectTo = '/test';

 public function __construct()
 {
     $this->middleware('guest', ['except' => 'getLogout']);

     $this->redirectTo = '/dashboard';
     $user = \Auth::user();
     if ( ($user->admin() ) {
     // an admin
         $this->redirectTo = '/admin';
     } else {
     // it's a client
         $this->redirectTo = '/client/dashboard';
     }
 }

 protected function validator(array $data)
 {
     return Validator::make($data, [
         'name' => 'required|max:255',
         'email' => 'required|email|max:255|unique:users',
         'password' => 'required|confirmed|min:6',
     ]);
 }

However, it still redirects everyone to /home. I've dd($this->redirectTo) and it shows the expected value.

How do I dynamically set the redirect path after a user has authenticated?

user151841
  • 17,377
  • 29
  • 109
  • 171
  • 1
    There is an updated answer for Laravel 5.4 here https://stackoverflow.com/a/45529876/3200896 – plexus Aug 06 '17 at 08:02

1 Answers1

1

You need to change the visibility of the redirectTo property to protected instead of private

So, change line 2 on AuthController to this;

protected $redirectTo = '/test';

When a property has private visibility, it can only be accessed within the same class (AuthController)

Laravel checks to see whether the $redirectTo property exists before redirecting after login. Because your $redirectTo property was private, it couldn't find it and therefore redirected to the default /home/.

halfer
  • 19,824
  • 17
  • 99
  • 186
JayIsTooCommon
  • 1,714
  • 2
  • 20
  • 30