首先使用composer安装类库
composer require mews/captcha
注册provider
'providers' => [
// ...
Mews\Captcha\CaptchaServiceProvider::class,
]
'aliases' => [
// ...
'Captcha' => 'Mews\Captcha\Facades\Captcha',
]
生存相应配置文件
php artisan vendor:publish
可以自定义自己的验证码样式,具体代码,请参照官方文档
Captcha.config 文件下
'login' => [
'length' => 4,
'width' => 80,
'height' => 30,
'quality' => 90,
'lines' => 6,
'bgImage' => false,
'bgColor' => '#ecf2f4',
'fontColors'=> ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
'contrast' => -5,
'angle' => 15,
]
创建相关验证码路由
//-----------------通用-验证码-------------------//
Route::get('create_code',['uses' => 'VerifyController@create_code','as' => 'create_code']);
Route::post('check_code',['uses' => 'VerifyController@check_code','as' => 'check_code']);
相应控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mews\Captcha\Facades\Captcha;
class VerifyController extends Controller{
public function create_code(){
return Captcha::create('login');
}
/**用于验证验证码**/
public function check_code(Request $request){
$validator = Captcha::check($request->input('verify'));
return response()->json($validator);
}
}
前台页面
<div class="form-code-img pull-left">
<img src="{{ route('create_code') }}" alt="" id="verify" name="login_code" onclick="this.src='{{ route('create_code') }}?r='+Math.random();" title="点击刷新">
</div>