Laravel6.x使用验证码mews/captcha
Laravel6.x中使用验证,从安装到到使用一气呵成。验证码是一个必须用到的功能,因此,做个简单的记录吧。对于其他版本未进行测试,如Laravel8。
安装验证码包
composer require mews/captcha
注册
app/config/app.php
'providers' => [
// ...
'Mews\Captcha\CaptchaServiceProvider',
]
'aliases' => [
// ...
'Captcha' => 'Mews\Captcha\Facades\Captcha',
]
配置
php artisan vendor:publish
执行该命令后出现如下选项阻塞执行
Which provider or tag's files would you like to publish?:
[0 ] Publish files from all providers and tags listed below
[1 ] Provider: Facade\Ignition\IgnitionServiceProvider
[2 ] Provider: Fideloper\Proxy\TrustedProxyServiceProvider
[3 ] Provider: Illuminate\Foundation\Providers\FoundationServiceProvider
[4 ] Provider: Illuminate\Mail\MailServiceProvider
[5 ] Provider: Illuminate\Notifications\NotificationServiceProvider
[6 ] Provider: Illuminate\Pagination\PaginationServiceProvider
[7 ] Provider: Intervention\Image\ImageServiceProviderLaravelRecent
[8 ] Provider: Laravel\Tinker\TinkerServiceProvider
[9 ] Provider: Mews\Captcha\CaptchaServiceProvider
[10] Tag: config
[11] Tag: flare-config
[12] Tag: ignition-config
[13] Tag: laravel-errors
[14] Tag: laravel-mail
[15] Tag: laravel-notifications
[16] Tag: laravel-pagination
输入 9 后会生成验证码配置文件app/config/captcha.php
视图使用验证码
案例
<img src="{{Captcha::src('default')}}">
完整案例:可刷新验证码
<div class="row cl">
<div class="formControls col-xs-8 col-xs-offset-3">
<input class="input-text size-L" name="code" type="text" placeholder="验证码" value="" style="width:150px;">
<img src="{{Captcha::src('default')}}" onclick="this.src=this.src+'?'+Math.random()" id="code">
<a href="javascript:;" onclick="document.getElementById('code').onclick()">看不清,换一张</a>
</div>
</div>
控制器中对验证码进行验证
表单请求验证
创建表单请求验证
php artisan make:request TestRequest
编写表单验证
// 一、改为true
public function authorize()
{
return true;
}
// 二、编写规则
public function rules()
{
return [
'code' => 'required|captcha'
];
}
控制器中注入
// app/Http/Controllers/TestController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\TestRequest;
class LoginController extends Controller
{
public function test(TestRequest $request)
{
}
}
2020-12-27
请登录后再评论