arjasco / laravel-recaptcha
轻松将reCAPTCHA添加到您的Laravel项目中
V1.1.0
2018-06-26 20:25 UTC
Requires
- guzzlehttp/guzzle: ~6.0
Requires (Dev)
- mockery/mockery: ^1.1
- orchestra/testbench: ~3.0
- phpunit/phpunit: ^7.2
This package is auto-updated.
Last update: 2023-09-29 02:13:06 UTC
README
此软件包允许您轻松地将reCAPTCHA添加到您的Laravel项目中。
安装
使用composer安装
composer require arjasco/laravel-recaptcha
如果您的Laravel版本不支持自动发现,请将服务提供者添加到您的app.php
配置文件中。
'providers' => [ ... Arjasco\LaravelRecpatcha\RecaptchaServiceProvider::class, ],
将配置文件发布到您的项目中。
php artisan vendor:publish --provider="Arjasco\LaravelRecaptcha\RecaptchaServiceProvider"
将您的站点密钥和密钥添加到recaptcha.php
。
return [ 'sitekey' => env('RECAPTCHA_SITEKEY'), 'secret' => env('RECAPTCHA_SECRET') ]
使用方法
表单嵌入
使用辅助函数recaptcha()
将HTML嵌入到您的表单中。
<form action="/contact" method="POST"> <input type="text" name="full_name" value=""/> <input type="text" name="email" value=""/> <textarea type="text" name="message"></textarea> <button>Send</button> {!! recaptcha() !!} </form>
或者,如果您使用Blade,可以使用@recaptcha
指令
<form action="/contact" method="POST"> ... @recaptcha </form>
您也可以向函数传递许多选项来进一步自定义嵌入。
<form action="/contact" method="POST"> ... {!! recaptcha(['theme' => 'dark', 'size' => 'compact']) !!} <!-- Or using the blade directive.. --> @recaptcha(['theme' => 'dark', 'size' => 'compact']) </form>
请参阅这里以获取更多选项的表格。使用选项数组时,省略每个选项的data-
部分。
验证
将recaptcha
规则添加到您想要验证的请求的验证器中。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ContactController extends Controller { public function send(Request $request) { $this->validate($request, [ 'g-recaptcha-response' => 'recaptcha' ]); } }
错误
验证过程中的任何错误都将添加到recaptcha
键中。例如,如果您只想获取第一个错误,您可能需要做以下操作:
<div class="form__errors"> {!! $errors->first('recaptcha', '<span>:message</span>') !!} </div>
自动脚本注入
如果您想自动将脚本注入到您的HTML头部标签中,只需将中间件添加到任何GET路由即可,这是可选的,您可能希望自行包含脚本。
在您的Kernel.php
文件中注册中间件。
<?php /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ ... 'recaptcha' => \Arjasco\LaravelRecaptcha\RecaptchaMiddleware::class, ];
在您的GET路由上使用中间件。
Route::get('/contact', 'ContactController@index')->middleware('recaptcha');