首页 文章

登录后,Laravel重定向回原始目的地

提问于
浏览
152

这似乎是一个非常基本的流程, Laravel 有很多很好的解决基本的东西,我觉得我错过了一些东西 .

用户单击需要身份验证的链接 . Laravel的auth过滤器启动并将它们路由到登录页面 . 用户登录,然后转到他们试图在'auth'过滤器启动之前到达的原始页面 .

有没有一种好方法可以知道他们最初想要访问哪个页面?由于Laravel是拦截请求的人,我不知道它是否在用户登录后跟踪某处以便轻松路由 .

如果没有,我很想知道你们中的一些人是如何手动实现的 .

18 回答

  • -1

    您可以使用 Redirect::intended 功能 . 它会将用户重定向到他们在被authenticaton过滤器捕获之前尝试访问的URL . 如果预期的目标不可用,则可以为该方法提供回退URI .

    在登录/注册后:

    return Redirect::intended('defaultpageafterlogin');
    
  • 6

    我在语言选择器代码上使用了一段时间 . 只要您只需要返回1页就可以了:

    return Redirect::to(URL::previous());
    

    它不是最强大的解决方案,但它非常简单,可以帮助解决一些难题 . :)

  • 0
    return Redirect::intended('/');
    

    这会将您重定向到项目的默认页面,即开始页面 .

  • 8

    对于laravel 5. *尝试这些 .

    return redirect()->intended('/');
    

    要么

    return Redirect::intended('/');
    
  • -1

    适用于Laravel 5.3及以上版本

    检查下面的Scott's answer .

    Laravel 5高达5.2

    简单的说,

    在auth中间件上:

    // redirect the user to "/login"
    // and stores the url being accessed on session
    if (Auth::guest()) {
        return redirect()->guest('login');
    }
    return $next($request);
    

    登录操作:

    // redirect the user back to the intended page
    // or defaultpage if there isn't one
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        return redirect()->intended('defaultpage');
    }
    

    对于Laravel 4(旧答案)

    在回答这个问题时,框架本身没有任何官方支持 . 现在你可以使用这个方法下面的bgdrl指出的方法:(我've tried updating his answer, but it seems he won' t接受)

    在身份验证过滤器上:

    // redirect the user to "/login"
    // and stores the url being accessed on session
    Route::filter('auth', function() {
        if (Auth::guest()) {
            return Redirect::guest('login');
        }
    });
    

    登录操作:

    // redirect the user back to the intended page
    // or defaultpage if there isn't one
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        return Redirect::intended('defaultpage');
    }
    

    对于Laravel 3(甚至更老的回答)

    您可以像这样实现它:

    Route::filter('auth', function() {
        // If there's no user authenticated session
        if (Auth::guest()) {
            // Stores current url on session and redirect to login page
            Session::put('redirect', URL::full());
            return Redirect::to('/login');
        }
        if ($redirect = Session::get('redirect')) {
            Session::forget('redirect');
            return Redirect::to($redirect);
        }
    });
    
    // on controller
    public function get_login()
    {
        $this->layout->nest('content', 'auth.login'); 
    }
    
    public function post_login()
    {
        $credentials = [
            'username' => Input::get('email'),
            'password' => Input::get('password')
        ];
    
        if (Auth::attempt($credentials)) {
            return Redirect::to('logged_in_homepage_here');
        }
    
        return Redirect::to('login')->with_input();
    }
    

    在Session上存储重定向有一个好处,即使用户错过键入他的凭据,或者他没有帐户并且必须注册,也可以保留它 .

    除了Auth之外,这还允许在会话上设置重定向,并且它会神奇地工作 .

  • 10

    Laravel> = 5.3

    由于Auth Middleware已移至服务容器,因此5.3中的Auth更改使得实现更容易,并且略微不同于5.2 .

    修改新的中间件身份验证重定向器

    /app/Http/Middleware/RedirectIfAuthenticated.php
    

    稍微改变手柄功能,看起来像:

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

    TL; DR说明

    唯一的区别在于第4行;默认情况下它看起来像这样:

    return redirect("/home");
    

    由于Laravel> = 5.3在检查Auth Guard时自动保存最后的“预期”路由,因此它将更改为:

    return redirect()->intended('/home');
    

    这告诉Laravel在登录前重定向到最后一个目标页面,否则转到“/ home”或默认情况下你想发送它们的任何地方 .

    希望这有助于其他人 - 5.2和5.3之间的区别并不多,特别是在这方面有很多 .

  • 4

    我找到了那两个可能对你非常有用的好方法 .

    Redirect::guest();
    Redirect::intended();
    

    您可以将此筛选器应用于需要身份验证的路由 .

    Route::filter('auth', function()
    {
        if (Auth::guest()) {
               return Redirect::guest('login');
        }
    });
    

    这种方法基本上是存储您尝试访问的页面,它会将您重定向到登录页面 .

    用户通过身份验证后即可致电

    return Redirect::intended();
    

    并且它会将您重定向到您最初尝试访问的页面 .

    虽然我通常使用以下方法,但这是一个很好的方法 .

    Redirect::back()
    

    你可以查看this真棒博客 .

  • 3

    Laravel 3

    我略微调整了您的(ViníciusFragosoPinheiro)代码,并将以下内容放在filters.php中

    Route::filter('auth', function()
    {
        // If there's no user authenticated session
        if (Auth::guest()) {
            // Flash current url to session and redirect to login page
            Session::flash('redirect', URL::full());
            return Redirect::guest('login');
        }
    });
    

    然后在我的AuthController.php中:

    // Try to log the user in.
    if (Auth::attempt($userdata)) {
    
        if ($redirect = Session::get('redirect')) {
            return Redirect::to($redirect);
        } else {
            // Redirect to homepage
            return Redirect::to('your_default_logged_in_page')->with('success', 'You have logged in successfully');
        }
    } else {
        // Reflash the session data in case we are in the middle of a redirect 
        Session::reflash('redirect');
    
        // Redirect to the login page.
        return Redirect::to('login')->withErrors(['password' => 'Password invalid'])->withInput(Input::except('password'));
    }
    

    请注意,如果存在身份验证问题,则会重新显示 'redirect' 会话数据 . 这可以在任何登录失败期间保持重定向不变,但是如果用户在任何时候点击,则下一个登录过程不会被会话数据中断 .

    您还需要在 AuthController 中显示登录表单时重新刷新数据,否则链断开:

    public function showLogin()
    {
        // Reflash the session data in case we are in the middle of a redirect 
        Session::reflash('redirect');
    
        // Show the login page
        return View::make('auth/login');
    }
    
  • -1

    使用 Redirect;

    然后用这个:

    return Redirect::back();
    
  • 47

    将LoginControllers构造函数更改为:

    public function __construct()
        {
            session(['url.intended' => url()->previous()]);
            $this->redirectTo = session()->get('url.intended');
    
            $this->middleware('guest')->except('logout');
        }
    

    它会在登录页面之前将您重定向回页面(2页返回) .

  • 3

    对于 Laravel 5.5 ,可能是5.4

    App\Http\Middleware\RedirectIfAuthenticated 中,在句柄功能中将 redirect('/home') 更改为 redirect()->intended('/home')

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

    App\Http\Controllers\Auth\LoginController 中创建 showLoginForm() 函数如下:

    public function showLoginForm()
    {
        if(!session()->has('url.intended'))
        {
            session(['url.intended' => url()->previous()]);
        }
        return view('auth.login');
    }
    

    这样,如果有另一个页面的意图,它将重定向到那里,否则它将重定向回家 .

  • -1

    对于Laravle 5.7,您需要更改为:

    中间件> RedirectIfAuthenticated.php

    改变这个:

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

    对此:

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

    return redirect('/ yourpath');

  • -1

    你在routes.php中尝试过这个吗?

    Route::group(['middleware' => ['web']], function () {
        //
        Route::get('/','HomeController@index');
    });
    
  • -1
    // Also place this code into base controller in contract function,            because ever controller extends base  controller
     if(Auth::id) {
      //here redirect your code or function
     }
    if (Auth::guest()) {
           return Redirect::guest('login');
    }
    
  • 19

    这是我的解决方案5.1 . 我需要有人点击帖子上的"Like"按钮,重定向到登录,然后返回到原始页面 . 如果他们已经登录,"Like"按钮的 href 被JavaScript拦截并变成了AJAX请求 .

    按钮类似于 <a href="/like/931">Like This Post!</a> . /like/931 由需要 auth 中间件的LikeController处理 .

    在Authenticate中间件( handle() 函数)中,在开头添加这样的内容:

    if(!str_contains($request->session()->previousUrl(), "/auth/login")) {
            $request->session()->put('redirectURL', $request->session()->previousUrl());
            $request->session()->save();
        }
    

    /auth/login 更改为您登录的URL . 此代码将原始页面的URL保存在会话中,除非URL是登录URL . 这是必需的,因为看起来好像这个中间件被调用了两次 . 我不确定为什么或者如果那个's true. But if you don' t检查该条件,它将等于正确的原始页面,然后以某种方式得到机会 /auth/login . 这可能是一种更优雅的方式 .

    然后,在 LikeController 或您拥有的任何控制器中处理原始页面上按下的按钮的URL:

    //some code here that adds a like to the database
    //...
    return redirect($request->session()->get('redirectURL'));
    

    这种方法非常简单,不需要覆盖任何现有的功能,而且效果很好 . Laravel可能有一些更简单的方法来做到这一点,但我不确定它是什么 . 使用 intended() 函数在我的情况下不起作用,因为LikeController还需要知道以前的URL重定向到它的内容 . 基本上是两级重定向 .

  • 0

    For Laravel 5.2 (以前的版本我没用过)

    将代码粘贴到app \ Http \ Controllers \ Auth \ AurhController.php文件中

    /**
     * Overrides method in class 'AuthenticatesUsers'
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showLoginForm()
    {
        $view = property_exists($this, 'loginView')
            ? $this->loginView : 'auth.authenticate';
        if (view()->exists($view)) {
            return view($view);
        }
        /**
         * seve the previous page in the session
         */
        $previous_url = Session::get('_previous.url');
        $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $ref = rtrim($ref, '/');
        if ($previous_url != url('login')) {
            Session::put('referrer', $ref);
            if ($previous_url == $ref) {
                Session::put('url.intended', $ref);
            }
        }
        /**
         * seve the previous page in the session
         * end
         */
        return view('auth.login');
    }
    /**
     * Overrides method in class 'AuthenticatesUsers'
     *
     * @param Request $request
     * @param $throttles
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function handleUserWasAuthenticated(Request $request, $throttles)
    {
        if ($throttles) {
            $this->clearLoginAttempts($request);
        }
        if (method_exists($this, 'authenticated')) {
            return $this->authenticated($request, Auth::guard($this->getGuard())->user());
        }
        /*return to the previous page*/
        return redirect()->intended(Session::pull('referrer'));
        /*return redirect()->intended($this->redirectPath()); /*Larevel default*/
    }
    

    并导入命名空间: use Session;

    如果您没有对文件app \ Http \ Controllers \ Auth \ AurhController.php进行任何更改,您只需将其替换为GitHub中的文件即可 .

  • 23

    Laravel 5.2

    如果您正在使用另一个中间件,如 Admin 中间件,则可以使用以下方法为url.intended设置会话:

    基本上我们需要手动设置 \Session::put('url.intended', \URL::full()); 进行重定向 .

    Example

    if (\Auth::guard($guard)->guest()) {
          if ($request->ajax() || $request->wantsJson()) {
             return response('Unauthorized.', 401);
          } else {
            \Session::put('url.intended', \URL::full());
            return redirect('login');
          }
      }
    

    On login attempt

    确保登录尝试使用 return \Redirect::intended('default_path');

  • 210

    Larvel 5.3 这只是通过更新LoginController.php实际上对我有用

    use Illuminate\Support\Facades\Session;
     use Illuminate\Support\Facades\URL;
    
    
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
        Session::set('backUrl', URL::previous());
    }
    
    
    public function redirectTo()
    {
        return Session::get('backUrl') ? Session::get('backUrl') :   $this->redirectTo;
    }
    

    参考:https://laracasts.com/discuss/channels/laravel/redirect-to-previous-page-after-login

相关问题