php 登录后 Laravel 5.4 重定向到自定义 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42177044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:33:28  来源:igfitidea点击:

Laravel 5.4 redirection to custom url after login

phpredirectlaravel-5

提问by ivanacorovic

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

我正在使用 Laravel Framework 5.4.10,并且我正在使用常规身份验证

php artisan make:auth

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

提供。我想保护整个应用程序,并在登录后将用户重定向到 /themes。

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

我有 4 个控制器:ForgotPasswordController.php、LoginController.php、RegisterController.php 和 ResetPasswordController.php。我已将此行编辑为最后三行:

protected $redirectTo = '/themes';

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

这是我的 routes/web.php 中的第一行:

Auth::routes();

I have added this function in my Controller.php:

我在我的 Controller.php 中添加了这个函数:

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

    }

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

我已经编辑了 app/Http/Middleware/RedirectIfAuthenticated.php,使 handle 函数看起来像这样:

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?

一切都很好,除了当我单击登录按钮时,我被重定向到“/”,而不是“/themes”。如果我不需要在控制器中进行身份验证(Controller.php 文件中没有 __contruct 函数),我会在登录时重定向到 OK。我究竟做错了什么?

回答by Babagana

That's what i am currrently working, what a coincidence.

这就是我目前正在工作的,真是巧合。

You also need to add the following lines into your LoginController

您还需要将以下行添加到您的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']);
}
}

回答by plexus

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.

如果您查看 AuthenticatesUsers 特征,您将看到在 sendLoginResponse 方法中调用了$this->redirectPath()。如果你查看这个方法,你会发现 redirectTo 可以是一个方法,也可以是一个变量。

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';
    }
}

回答by Amirul

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

我通过使用 AuthenticatesUsers 特性来完成它的方式。

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

\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');
}

回答by WPZA

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

对于Laravel的更新版本,请更换protected $redirectTo = RouteServiceProvider::HOME;protected $redirectTo = '/newurl';并更换newurl相应。

Tested with Laravel version-6

使用 Laravel 版本 6 进行测试

回答by Farid Movsumov

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

您应该将 $redirectTo 值设置为要重定向的路由

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

inside AuthController constructor.

在 AuthController 构造函数中。

/**
 * 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');
}

回答by robby dwi hartanto

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

您可以在 LoginController 添加行use App\User;的顶部添加方法,在此添加方法之后,它对我有用 wkwkwkwkw ,但您必须添加 {{ csrf_field() }}视图管理员和用户

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');

}}

回答by Giuseppe Muci

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

根据Laravel 文档,我在 app/Http/Controllers/Auth/LoginController.php 中创建了以下方法:

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

为了从我的数据库中获取用户信息,我使用了“Illuminate\Support\Facades\Auth;”。