如果自定义一个 Captcha 验证规则放到 FormRequest 中,就可以把控制器里的验证过程去掉了 
                            
                                                    
                        
                    
                    
  
                    
                    我是这么实现的,欢迎指正
(我用的是邮箱验证,在请求验证码的时候就验证邮箱是不是存在)
新建一个验证规则Captcha
app/Rules/Captcha.php
<?php
namespace App\Rules;
use Dingo\Api\Http\FormRequest;
use Illuminate\Contracts\Validation\Rule;
class Captcha implements Rule
{
    protected $request = null;
    /**
     * @var int $inValidFlag
     *
     * 1 => 超时
     * 2 => 验证码不正确
     * 3 => 邮箱不正确
     */
    protected $inValidFlag = 0;
    public function __construct(FormRequest $request)
    {
        $this->request = $request;
    }
    public function passes($attribute, $captcha)
    {
        $result = true;
        $cache = \Cache::get($captcha['key']);
        \Cache::forget($captcha['key']);
        if (empty($cache)) {
            $result = false;
            $this->inValidFlag = 1;
        } elseif (!hash_equals($cache['code'], $captcha['code'])) {
            $result = false;
            $this->inValidFlag = 2;
        } elseif (!hash_equals($cache['email'], $this->request->input('email'))) {
            $result = false;
            $this->inValidFlag = 3;
        }
        return $result;
//        return empty($cache) ? false :
//            hash_equals($cache['code'], $captcha['code']) && hash_equals($cache['email'], $this->request->only('email'));
    }
    public function message()
    {
        switch ($this->inValidFlag) {
            case 1:
                return "验证超时";
            case 2:
                return "验证码不正确";
            case 3:
                return "验证邮箱不正确";
        }
    }
}
在 Request 中调用
    public function rules()
    {
        return [
            .
            .
            .
            'captcha' => ['required', 'some other rule', new Captcha($this)],
        ];
    }
                        
                                                    
                        
                                            
          
                    
                    

          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: