laravel 5.5 登录验证码 captcha 引入

前提: 开启Laravel的用户认证功能

1、安装 Captcha

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
安装 Captcha+

$ composer require mews/captcha

配置

/config/app.php
'providers' => [
// ...
Mews\Captcha\CaptchaServiceProvider::class,
]
'aliases' => [
// ...
'Captcha' => Mews\Captcha\Facades\Captcha::class,
]

自定义配置
$ php artisan vendor:publish

运行之后,就可以在 config/captcha.php 中进行配置了。这里使用默认配置。

2、使用 Captcha 为 auth 组件添加验证码功能

在登录视图中增加验证码的选项,可以加到密码和 remember me 之间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/resources/views/auth/login.blade.php
<div class="form-group">
<label for="captcha" class="col-md-4 control-label">验证码</label>
<div class="form-group">
<div class="col-md-3">
<input id="captcha" class="form-control" type="captcha" name="captcha" value="{{ old('captcha') }}" required>
@if($errors->has('captcha'))
<div class="col-md-12">
<p class="text-danger text-left"><strong>{{$errors->first('captcha')}}</strong></p>
</div>
@endif
</div>
<div class="col-md-4">
<img src="{{captcha_src()}}" style="cursor: pointer" onclick="this.src='{{captcha_src()}}'+Math.random()">
</div>
</div>
</div>

重写 AuthController 登录验证方法,并自定义提示信息:
修改 AppHttpControllersAuthLoginController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
首先要引入如下代码:
use Illuminate\Http\Request;

重写validateLogin方法:

在验证里面加入验证码的规则验证即可
/**
* DESC: 重写 AuthenticatesUsers 登录验证方法,并自定义提示信息;
* 原验证方法 Illuminate\Foundation\Auth\AuthenticatesUsers
* @param Request $request
*/
protected function validateLogin(Request $request){
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
'captcha' => 'required|captcha',
],[
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
}