53

I am using Laravel Framework 5.4.10, and I am using the regular authentication that

php artisan make:auth

provides. I want to protect the entire app, and to redirect users to /themes after login.

I have 4 controllers: ForgotPasswordController.php, LoginController.php, RegisterController.php and ResetPasswordController.php. I have edited this line into the last three:

protected $redirectTo = '/themes';

This is the first line in my routes/web.php:

Auth::routes();

I have added this function in my Controller.php:

    public function __construct()
    {
        $this->middleware('auth');

    }

I have edited app/Http/Middleware/RedirectIfAuthenticated.php, so that the handle function looks like this:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/themes');
    }

    return $next($request);
}

It's all fine, except when I click the Login button, I get redirected to "/", not "/themes". If I don't require authentication in the controllers (no __contruct function in Controller.php file), I get redirected OK at login. What am I doing wrong?

ivanacorovic
  • 2,415
  • 3
  • 26
  • 41
  • https://laracasts.com/discuss/channels/general-discussion/redirect-to-profile-after-login?page=1&replyId=174180 – shasi kanth Sep 22 '21 at 05:30

9 Answers9

95

You need to add the following lines into your LoginController:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/

use AuthenticatesUsers;


protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
    return redirect()->route('dashboard');
}

 return redirect('/home');
}
/**
 * Where to redirect users after login.
 *
 * @var string
 */
//protected $redirectTo = '/admin';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}
}
Undo
  • 25,381
  • 37
  • 106
  • 126
Babagana
  • 976
  • 7
  • 4
  • Great! The only thing is that isAdmin() gave me a BadMethodCallException, so I skipped the whole IF part and it worked perfectly! – ivanacorovic Feb 12 '17 at 02:32
  • 2
    I am glad it helped, my application uses isAdmin() to check wether the user is an Admin before redirection, could'nt have the chance to change according your code just wanted to give you a hint. Thanks – Babagana Feb 12 '17 at 15:00
  • Hmm, wouldn't it be possible also to obtain the authenticated user with the Auth facade?, import it with `use Auth;` and then to obtain user you would do `$user = Auth::user();`. – Aarón Gutiérrez Feb 20 '19 at 22:12
17

If you look in the AuthenticatesUsers trait you will see that in the sendLoginResponse method that there is a call made to $this->redirectPath(). If you look at this method then you will discover that the redirectTo can either be a method or a variable.

This is what I now have in my auth controller.

public function redirectTo() {
    $user = Auth::user();
    switch(true) {
        case $user->isInstructor():
            return '/instructor';
        case $user->isAdmin():
        case $user->isSuperAdmin():
            return '/admin';
        default:
            return '/account';
    }
}
Community
  • 1
  • 1
plexus
  • 302
  • 4
  • 7
  • Redirecting using access roles can be done this way using the Bouncer library as well (for those not writing there own access control methods). Just change "case $user->isInstructor():" to "case Bouncer::allows('isInstructor', $user):". You will obviously need to have the 'isInstructor' ability added to the users role. If anyone wants me to post the Bouncer code I use in my controller let me know. – AKMorris Sep 26 '17 at 03:35
  • This is much cleaner. You are amazing! – S. Farooq Oct 27 '19 at 11:27
  • Are the isAdmin(), etc. methods already defined by Laravel or did you have to define them ? – Mason H. Hatfield Mar 22 '20 at 16:22
  • @MasonH.Hatfield You have to define them for your application. You can also use other methods of handling this, such as the above comment from AKMorris about [Bouncer](https://github.com/JosephSilber/bouncer). – Moshe Katz May 06 '20 at 17:46
15

The way I've done it by using AuthenticatesUsers trait.

\App\Http\Controllers\Auth\LoginController.php

Add this method to that controller:

/**
 * Check user's role and redirect user based on their role
 * @return 
 */
public function authenticated()
{
    if(auth()->user()->hasRole('admin'))
    {
        return redirect('/admin/dashboard');
    } 

    return redirect('/user/dashboard');
}
Amirul
  • 472
  • 6
  • 15
4

For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME; with protected $redirectTo = '/newurl'; and replace newurl accordingly.

Tested with Laravel version-6

WPZA
  • 793
  • 8
  • 27
4

Path Customization (tested in laravel 7) When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider:

public const HOME = '/home';
Murad
  • 883
  • 10
  • 10
1

You should set $redirectTo value to route that you want redirect

$this->redirectTo = route('dashboard');

inside AuthController constructor.

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';

/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    $this->redirectTo = route('dashboard');
}
Farid Movsumov
  • 11,576
  • 8
  • 70
  • 94
1
  1. Go to Providers->RouteServiceProvider.php

  2. There change the route, given below:

    class RouteServiceProvider extends ServiceProvider
    {
     protected $namespace = 'App\Http\Controllers';
    
     /**
      * The path to the "home" route for your application.
      *
      * @var string
      */
     public const HOME = '/dashboard';
    
ßãlãjî
  • 6,894
  • 3
  • 32
  • 37
Nazmul Haque
  • 457
  • 5
  • 11
0

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}
robby dwi hartanto
  • 307
  • 1
  • 3
  • 6
0

in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :

protected function redirectTo()
{
    $user=Auth::user();

    if($user->account_type == 1){
        return '/admin';
    }else{
        return '/home';
    }

}

to get the user information from my db I used "Illuminate\Support\Facades\Auth;".