安装

首先使用Composer安装mews/captcha扩展包:

  1. composer require mews/captcha

安装配置项

php artisan vendor:publish --provider='Mews\Captcha\CaptchaServiceProvider'

配置文件安装完毕 :
image.png
配置项内容很容易读懂

return [
    'characters' => ['2', '3', '4', '6', '7', '8', '9'],
    'default' => [
        'length' => 9,
        'width' => 120,
        'height' => 36,
        'quality' => 90,
        'math' => false,
        'expire' => 60,
        'encrypt' => false,
    ],
    'math' => [
        'length' => 9,
        'width' => 120,
        'height' => 36,
        'quality' => 90,
        'math' => true,
    ],

    'flat' => [
        'length' => 6,
        'width' => 160,
        'height' => 46,
        'quality' => 90,
        'lines' => 6,
        'bgImage' => false,
        'bgColor' => '#ecf2f4',
        'fontColors' => ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
        'contrast' => -5,
    ],
    'mini' => [
        'length' => 3,
        'width' => 120,
        'height' => 60,
    ],
    'inverse' => [
        'length' => 5,
        'width' => 120,
        'height' => 36,
        'quality' => 90,
        'sensitive' => true,
        'angle' => 12,
        'sharpen' => 10,
        'blur' => 2,
        'invert' => true,
        'contrast' => -5,
    ]
];

使用

此扩展包的使用分为两步:

  1. 前端展示 —— 生成验证码给用户展示,并收集用户输入的答案;
  2. 后端验证 —— 接收答案,检测用户输入的验证码是否正确。

    1. 前端展示

    接下来我们请将注册页面模板 register.blade.php 内容替换为以下:
    resources/views/auth/register.blade.php
    展示验证码图片的标签是 :

    {{ captcha_src('mini') }}
    

    放入到图片标签中 :

    <div class="form-group row">
    <label for="captcha" class="col-md-4 col-form-label text-md-right">验证码</label>
    <div class="col-md-6">
     验证码 : <input type="text" name="code">
     <img src="{{ captcha_src('mini') }}" onclick="this.src='/captcha/mini?'+Math.random()" title="点击图片重新获取验证码">
    
     @if ($errors->has('captcha'))
       <span class="invalid-feedback" role="alert">
         <strong>{{ $errors->first('captcha') }}</strong>
       </span>
     @endif
    </div>
    </div>
    

    2. 后端验证

    mews/captcha 是专门为 Laravel 量身定制的扩展包,能很好的兼容 Laravel 生成的注册逻辑。我们只需要在注册的时候,添加上表单验证规则即可:
    app/Http/Controllers/Auth/RegisterController.php

    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' => '请输入正确的验证码',
     ]);
    }