Laravel 5.4 redirection to custom url after login

前端 未结 9 2178
悲哀的现实
悲哀的现实 2020-11-28 09:46

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

相关标签:
9条回答
  • 2020-11-28 10:08

    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;".

    0 讨论(0)
  • 2020-11-28 10:10

    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');
    }
    
    0 讨论(0)
  • 2020-11-28 10:11

    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');
    }
    
    0 讨论(0)
  • 2020-11-28 10:15

    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');
    
    }}
    
    0 讨论(0)
  • 2020-11-28 10:19

    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';
    
    0 讨论(0)
  • 2020-11-28 10:25

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

    Tested with Laravel version-6

    0 讨论(0)
提交回复
热议问题