laravel框架——验证码(第二种方法)

开发环境:

laravel5.5

php7.1.11

mysql

 

一、安装扩展包 ,安装前确认当前环境支持composer(出现如下图所示则安装成功)

$ composer require "mews/captcha:~2.0"

二、安装完成后执行:$ php artisan vendor:publish 生成配置文件config/captcha

三、视图文件代码:

<tr>
    <td>验证码</td> 
    <td><input name="captcha" type="text" placeholder="请输入验证码"></td>     
    <td>
          <img class="thumbnail captcha" src="{{ captcha_src('flat') }}" onclick="this.src='/captcha/flat?'+Math.random()" title="点击图片重新获取验证码">
    </td>

代码释义:

1、captcha_src() 方法是 mews/captcha 提供的辅助方法,用于生成验证码图片链接

2、『验证码』区块中 onclick() 是 JavaScript 代码,实现了点击图片重新获取验证码的功能,允许用户在验证码太难识别的情况下换一张图片试试

四、控制器检验

$code = $this->validate($request, [
'captcha' => 'required|captcha'
]);

在Auth目录下的Register控制器重写方法:

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'captcha'=>'required|captcha',
        ],[
            'captcha.required' => '验证码不能为空',
            'captcha.captcha' => '请输入正确的验证码',
        ]);
    }

由于captcha在中文包中没有中文解释,所以需要手动添加中文解释,具体操作如下:

首先下载字体库:

链接: https://pan.baidu.com/s/1YhtjKc6bpWGHCNRxhnSmKg

提取码: mrxv 

然后解压缩将src目录下的zh-CN放入resources目录下然后在validation.php中添加

在return中添加:'captcha' => ':attribute 不正确。',

在 attributes中添加:'captcha' => '验证码',

然后在config/app.php中修改:'locale' => 'zh-CN',

这样就完成了!

posted @ 2019-04-11 21:09  你的男孩  阅读(482)  评论(0编辑  收藏  举报