Laravel重定向在事件处理程序/侦听器中不起作用 [英] Laravel Redirect does not work in Event handler / listener

查看:69
本文介绍了Laravel重定向在事件处理程序/侦听器中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Auth.Attempt事件处理程序类,该类可以检测用户的登录尝试来决定锁定用户的帐户. 但是,当我尝试通过Flash消息将用户重定向到登录页面时,我发现重定向不起作用,它仍在进行下一步. 我想在事件中中断该过程,并提供我的自定义警告消息.谁能帮我吗?非常感谢.

I have a Auth.Attempt event handler class, which I detect user's login attempts to decide to lock user's account. However, when I tried to redirect user to login page with a flash message, I found the redirection does not work, it's still carry on next step. I want to interrupt the process in the event and give my custom warning message. Can anyone help me out? Thanks a lot.

我的事件处理程序:

namespace MyApp\Handlers\Security;

use DB;
use Session;
use Redirect;

class LoginHandler 
{
    /**
     * Maximum attempts
     * If user tries to login but failed more than this number, User account will be locked
     * 
     * @var integer
     */
    private $max_attemtps;

    /**
     * Maximum attempts per IP
     * If an IP / Device tries to login but failed more than this number, the IP will be blocked
     * 
     * @var integer
     */
    private $ip_max_attempts;

    public function __construct()
    {
        $this->max_attempts = 10;
        $this->ip_max_attempts = 5;
    }

    public function onLoginAttempt($data)
    {
        //detection process.......
        // if login attempts more than max attempts
        return Redirect::to('/')->with('message', 'Your account has been locked.');
    }
}

现在我的操作方式如下:

Now the way I am doing this is like below:

Session::flash('message', 'Your account has been locked.');
header('Location: '.URL::to('/'));

它可以工作,但是我不确定这是否是完美的方法.

It works but I am not sure if it's perfect way to do it.

推荐答案

在这个非常有趣的讨论中没有做太多的事情:

Not getting to much into this very interesting discussion:

您可以尝试设置自己的异常处理程序,然后从那里重定向到登录页面.

You can try setting up your own exception handler and redirect from there on to the login page.

class FancyException extends Exception {}

App::error(function(FancyException $e, $code, $fromConsole)
{
    $msg = $e->getMessage();        
    Log::error($msg);

    if ( $fromConsole )
    {
        return 'Error '.$code.': '.$msg."\n";
    }

    if (Config::get('app.debug') == false) {
        return Redirect::route('your.login.route');
    }
    else
    {
        //some debug stuff here
    }


});

在您的函数中:

public function onLoginAttempt($data)
{
    //detection process.......
    // if login attempts more than max attempts
    throw new FancyException("some msg here");
}

这篇关于Laravel重定向在事件处理程序/侦听器中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆