Laravel 無痛使用 recaptcha 不用科學 sw

XiaohuiLam發表於2018-12-02

以 laravel5.7 登入為例。

步驟

首先

composer require 233sec/laravel-recaptchav3

修改 App\Http\Controllers\Auth\LoginController, 新增如下方法

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
            'g-recaptcha-response' => 'required|recaptchav3:login,0.5', // 重點在這一行
        ]);
    }

修改 resources/views/auth/login.blade.php
<button type="submit"...> 之前加入如下程式碼

            <div class="form-group
            @if ($errors->has('g-recaptcha-response'))
            has-error
            has-feedback
            @endif
            ">
                {!! RecaptchaV3::field('login') !!}
                @if ($errors->has('g-recaptcha-response'))
                    <span class="glyphicon glyphicon-warning-sign form-control-feedback" aria-hidden="true"></span>
                    <span class="help-block">{{ $errors->first('g-recaptcha-response') }}</span>
                @endif
            </div>

並在你的模板 javascript

@push('script')
    {!! RecaptchaV3::initJs() !!}
@endpush

.env 加入如下

RECAPTCHAV3_SITEKEY=#你的sitekey#
RECAPTCHAV3_SECRET=#你的secret#
RECAPTCHAV3_ORIGIN=https://www.recaptcha.net #這一行特別重要,否則在大陸無法使用

驗證訊息自定義

修改 resources/lang/#你的語言設定#/validation.php

<?php
return [
    ...,
    'custom' => [
        'g-recaptcha-response' => [
            'recaptchav3' => '驗證碼錯誤'
        ]
    ],

    'attributes' => [
        'g-recaptcha-response' => '驗證碼',
    ]
];

效果

file
file

來源

Fine or not, never stop. Laravel 執行生命週期解析

相關文章