laravel5通过auth.attempt事件加入登陆验证码

<?php namespace WangDongHttpControllersAuth;

use IlluminateHttpExceptionHttpResponseException;
use IlluminateHttpRequest;
use WangDongHttpControllersController;
use IlluminateContractsAuthGuard;
use IlluminateContractsAuthRegistrar;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;

class AuthController extends Controller {

    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers;

    /**
     * Create a new authentication controller instance.
     *
     * @param  IlluminateContractsAuthGuard  $auth
     * @param  IlluminateContractsAuthRegistrar  $registrar
     * @return void
     */
    public function __construct(Guard $auth, Registrar $registrar,Request $request)
    {
        $this->auth = $auth;
        $this->registrar = $registrar;
        //注册auth.attemp事件
        //加入验证码的验证
        $this->auth->attempting(function()use($request){
            $phrase = Session::get('phrase');
            if($request->input('phrase') != $phrase){
                throw new HttpResponseException(
                    redirect('/auth/login')->withInput($request->input())->withErrors(['phrase'=>'验证码错误'])
                );
            }
        });
        $this->middleware('guest', ['except' => 'getLogout']);
    }

}

需要特别说明的是HttpResponseException这个异常,这个异常接收一个Response作为参数,在IlluminateRoutingRoute的run方法中会捕获这个异常并返回设置的Response,所以我们可以通过抛出这个异常来终止我们的应用程序并跳转

    public function run(Request $request)
    {
        $this->container = $this->container ?: new Container;

        try
        {
            if ( ! is_string($this->action['uses']))
                return $this->runCallable($request);

            if ($this->customDispatcherIsBound())
                return $this->runWithCustomDispatcher($request);

            return $this->runController($request);
        }
        catch (HttpResponseException $e)
        {
            return $e->getResponse();
        }
    }    
原文地址:https://www.cnblogs.com/xiaodo0/p/4397982.html