Laravel - 驗證碼(captcha)

PHPSIX發表於2017-11-14
  • 本人感覺用的比較好的驗證碼包,拿出來分享一下,傻瓜式教程,大佬別噴。:smile: :smile: :smile:
  • 安裝步驟:
    • 首先,登入網址packagist.org查詢 laravel captcha,找到mews/captcha ,根據packagist上的使用方法一步步來實現驗證碼的安裝。
    • composer安裝:composer require mews/captcha
    • 註冊providers (config/app.php) ,在這個陣列中的最後追加如下程式碼:
      Mews\Captcha\CaptchaServiceProvider::class,
    • 註冊aliases (config/app.php),在這個陣列中的最後追加如下程式碼:
      'Captcha' => Mews\Captcha\Facades\Captcha::class,
    • 生成配置檔案,在Composer命令列中輸入如下命令:
      php artisan vendor:publish
    • 進入config/captcha.php 檔案,修改default 陣列 可以對驗證碼進行樣式、數量、大小上的修改。
      'default'   => [
      'length'    => 5,
      'width'     => 100,
      'height'    => 34,
      'quality'   => 90,
      ],
  • 頁面中使用:
<div class="row">
    <div class="col-md-8">
        <input type="text" class="form-control {{$errors->has('captcha')?'parsley-error':''}}" name="captcha" placeholder="captcha">
    </div>
    <div class="col-md-4">
        <img src="{{captcha_src()}}" style="cursor: pointer" onclick="this.src='{{captcha_src()}}'+Math.random()">
    </div>
    @if($errors->has('captcha'))
        <div class="col-md-12">
            <p class="text-danger text-left"><strong>{{$errors->first('captcha')}}</strong></p>
        </div>
    @endif
</div>
  • 點選圖片重新整理,如下程式碼:
<img src="{{captcha_src()}}" style="cursor: pointer" onclick="this.src='{{captcha_src()}}'+Math.random()">
  • 重寫AuthController 登入驗證方法,並自定義提示資訊:

    • 首先要引入如下程式碼:
      use Illuminate\Http\Request;

    • 重寫validateLogin方法:

 protected function validateLogin(Request $request){
        $this->validate($request, [
            $this->loginUsername() => 'required',
            'password' => 'required',
            'captcha' => 'required|captcha',
        ],[
            'captcha.required' => trans('validation.required'),
            'captcha.captcha' => trans('validation.captcha'),
        ]);
    }
  • 字型庫的下載與切換:
    • 首先需要下載字型庫
    • 下載完成後,將壓縮包中 src/zh-CN 資料夾複製到專案目錄的 resources/lang 資料夾下。
    • 修改 config->app.php 檔案,修改程式碼如下:
      'locale' => 'zh-CN',
  • 由於captcha在中文包中沒有中文解釋,所以需要手動新增中文解釋,具體操作如下:
    • 開啟 resources/zh-CN/validation.php,在總陣列中追加如下鍵值對:
      'captcha'                  => ':attribute 不正確。',
    • 在 attributes 陣列中追加如下鍵值對:
      'captcha'               => '驗證碼',
本作品採用《CC 協議》,轉載必須註明作者和本文連結
老郭部落格:laughing: 個人部落格地址:www.phpsix.com

相關文章