重写和推荐的方法。
手册供参考https://laravel.com/docs/5.5/validation#creating-form-requests https://laravel.com/docs/5.5/validation#creating-form-requests
使用请求文件。
- run
php artisan make:request UpdateUserPasswordRequest
- 写入请求文件
2020 年 2 月编辑:在最新版本的 Laravel 中,授权方法中可以使用全局 auth() 对象代替 \Auth,因此 \Auth::check() 将变为 auth()->check()。如果从框架中删除某些内容,两者仍然有效并且会更新
<?php
namespace App\Http\Requests;
class UpdateUserPasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return \Auth::check();
// In laravel 8 use Auth::check()
// edit you can now replace this with return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'username' => 'required|max:255',
'oldpassword' => 'required|max:255',
'newpassword' => 'required|min:6|max:255|alpha_num',
'newpasswordagain' => 'required|same:newpassword',
];
}
/**
* Get the validation attributes that apply to the request.
*
* @return array
*/
public function attributes()
{
return [
'username' => trans('userpasschange.username'),
'oldpassword' => trans('userpasschange.oldpassword'),
'newpassword' => trans('userpasschange.newpassword'),
'newpasswordagain' => trans('userpasschange.newpasswordagain'),
];
}
/**
* Get the validation messages that apply to the request.
*
* @return array
*/
public function messages()
{
// use trans instead on Lang
return [
'username.required' => Lang::get('userpasschange.usernamerequired'),
'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
'oldpassword.max' => Lang::get('userpasschange.oldpasswordmax255'),
'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
'newpassword.min' => Lang::get('userpasschange.newpasswordmin6'),
'newpassword.max' => Lang::get('userpasschange.newpasswordmax255'),
'newpassword.alpha_num' =>Lang::get('userpasschange.newpasswordalpha_num'),
'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
'username.max' => 'The :attribute field must have under 255 chars',
];
}
- 在用户控制器中
<?php namespace App\Http\Controllers;
// VALIDATION: change the requests to match your own file names if you need form validation
use App\Http\Requests\UpdateUserPasswordRequest as ChangePassRequest;
//etc
class UserCrudController extends Controller
{
public function chnagePassword(ChangePassRequest $request)
{
// save new pass since it passed validation if we got here
}
}