在 Laravel 8 中使用验证码并验证的步骤如下:
1.安装验证包:
composer require mews/captcha
2.发布配置文件
php artisan vendor:publish --provider="Mews\Captcha\CaptchaServiceProvider"
3.在web.php文件中添加路由
// 生成验证码图片
Route::get('captcha', 'CaptchaController@captcha')->name('captcha');
4.创建控制器中验证码方法
namespace App\Http\Controllers;
use Mews\Captcha\Facades\Captcha;
class CaptchaController extends Controller
{
public function captcha()
{
return Captcha::create('default');
}
}
5. 在视图中添加显示验证码的 HTML 元素和用于刷新验证码的链接:
<form method="POST" action="/submit-form">
@csrf
<input type="text" name="captcha" class="form-control" placeholder="Enter the captcha">
<img src="{{ route('captcha') }}" id="captcha-img" data-route="{{ route('captcha.refresh') }}" style="cursor: pointer;">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('captcha-img').onclick = function() {
this.src = this.src + '?refresh=' + Math.random();
};
</script>
6. 在表单提交的路由中添加验证码验证逻辑:
use Illuminate\Http\Request;
use Mews\Captcha\Facades\Captcha;
Route::post('/submit-form', function (Request $request) {
$request->validate([
'captcha' => 'required|captcha'
]);
// 验证码验证通过后的逻辑...
});