我在请求类中有一个非常简单的规则方法,如下所示。
public function rules()
{
return [
'Subject' => 'required|max:50',
'Description' => 'required|max:500',
'DepartmentID' => 'required|integer|min:1',
'PriorityID' => 'required|integer|min:1'
];
}
内部控制器操作方法,下面是代码。
private function SaveChanges(\App\Http\Requests\TicketRequest $request) {
$v = \Validator::make($request->all(), [
]);
$DepartmentAdmins = $this->getDepartmentAdmins();
//Check if department admin missing then no need to add the record
if($DepartmentAdmins == null || count($DepartmentAdmins) == 0) {
$v->errors()->add('MissingAdmins', 'Department admin missing.');
return redirect()->back()->withErrors($v->errors());
}
}
问题:
正如我们在rule
方法中看到的那样,有4个表单字段。有没有办法将部门管理员的检查从Controller Action方法转移到request
类?
答案 0 :(得分:7)
Laravel的Request
具有after
挂钩,可在正常验证完成后运行。这就是你如何在你的情况下使用它:
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Models\Property;
use Illuminate\Validation\Validator;
class SomeRequest extends Request
{
/**
* Get the validator instance for the request.
*
* @return Validator
*/
protected function getValidatorInstance()
{
$instance = parent::getValidatorInstance();
$instance->after(function ($validator) {
$this->validateDepartmentAdmins($validator);
});
return $instance;
}
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'Subject' => 'required|max:50',
'Description' => 'required|max:500',
'DepartmentID' => 'required|integer|min:1',
'PriorityID' => 'required|integer|min:1'
];
}
/**
* @param Validator $validator
*/
public function validateDepartmentAdmins(Validator $validator)
{
$DepartmentAdmins = $this->getDepartmentAdmins();
//Check if department admin missing then no need to add the record
if($DepartmentAdmins == null || count($DepartmentAdmins) == 0) {
$validator->errors()->add('MissingAdmins', 'Department admin missing.');
}
}
这样您就不必在SaveChanges控制器方法中进行任何验证。
此代码在Laravel 5.1中使用,但我相信它在5.2中的工作方式相同。
答案 1 :(得分:1)
表单请求类基本上有两种方法。 "授权"和"规则"。更改部门管理员存在检查的最佳方法是添加您自己的自定义验证器(例如命名为" adminCountValidator")并实施您的逻辑以检查那里的管理员数量。然后在"规则"中使用yoir新定义的验证器。像这样的方法:
public function rules()
{
return [
'Subject' => 'required|max:50',
'Description' => 'required|max:500',
'DepartmentID' => 'required|integer|min:1|adminCountValidator',
'PriorityID' => 'required|integer|min:1'
];
}
如果您定义了客户验证规则,您还可以定义相关的错误消息,您的控制器操作将更加清晰。这是用于定义自己的自定义验证器的链接
custom-validation-rules
以下是在服务提供商中添加自定义验证程序的示例代码
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('adminCountValidator', function($attribute, $value, $parameters, $validator) {
/*
implement your getDepartmentAdmins()
function here and return true or false
*/
});
}