安装验证码库(具体安装参看文档)
composer require mews/captcha
复制vendor/encore/laravel-admin/src/Controllers/AuthController.php到app/Admin/Controllers/AuthController.php,修改代码如下
<?php
namespace App\Admin\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
/**
* Login page.
*
* @return \Illuminate\Contracts\View\Factory|Redirect|\Illuminate\View\View
*/
public function getLogin()
{
if (!Auth::guard('admin')->guest()) {
return redirect(config('admin.route.prefix'));
}
return view('admin.login');
}
/**
* @param Request $request
*
* @return mixed
*/
public function postLogin(Request $request)
{
$credentials = $request->only(['username', 'password','captcha']);
$validator = Validator::make($credentials, [
'username' => 'required',
'password' => 'required',
'captcha' => 'required|captcha'
]);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
unset($credentials['captcha']);
if (Auth::guard('admin')->attempt($credentials)) {
admin_toastr(trans('admin.login_successful'));
return redirect()->intended(config('admin.route.prefix'));
}
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
/**
* @return string|\Symfony\Component\Translation\TranslatorInterface
*/
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? trans('auth.failed')
: 'These credentials do not match our records.';
}
}
php artisan vendor:publish 发布,选择11
在resources/lang/zh-CN/validation.php中添加
'captcha' => ':attribute 错误',
'attributes' => [
'captcha' => '验证码',
//...
]
复制vendor/encore/laravel-admin/resources/views/login.blade.php到resources/views/admin/login.blade.php。
新增内容如下:
<div class="form-group has-feedback {!! !$errors->has('captcha') ?: 'has-error' !!}">
@if($errors->has('captcha'))
@foreach($errors->get('captcha') as $message)
<label class="control-label" for="inputError"><i class="fa fa-times-circle-o"></i>{{$message}}</label></br>
@endforeach
@endif
<input type="text" class="form-control" style="display: inline;width: 60%" placeholder="{{ trans('admin.captcha') }}" name="captcha">
<span class="glyphicon glyphicon-refresh form-control-feedback captcha" style="right:39%;z-index: 100"></span>
<img style="display: inline;width: 37%;height: 36px;float: right" class="captcha" src="{{ captcha_src('admin') }}">
</div>
<script>
$(function () {
$('.captcha').click(function () {
$('img[class="captcha"]').attr('src','{{ captcha_src('admin') }}'+Math.random());
});
});
</script>
app/Admin/routes.php中新增
$router->get('auth/login', 'AuthController@getLogin');
$router->post('auth/login', 'AuthController@postLogin');
覆盖原先路由