【发布时间】:2017-07-19 06:42:28
【问题描述】:
我有我的自定义请求,它扩展了 Backpack CrudController。
现在我想覆盖 ValidatesWhenResolvedTrait 的 prepareForValidation,因为它看起来是修改传入数据的正确位置,但我不知道如何...
所以我的第一个问题是,我可以覆盖这个方法吗?它受保护...
protected function prepareForValidation()
我的第二个问题是,如何修改我对 Request 或 FormRreuqest 对象的输入?
这是我的请求类
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Config;
class DonationsRequest extends \Backpack\CRUD\app\Http\Requests\CrudRequest
{
/**
* 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();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email',
'dob' => 'required|date',
'newsletter' => 'required|boolean',
'country' => 'sometimes|required|in:'.implode(',', Config::get('validation.countries')),
'street' => 'sometimes|required|string|max:255',
'zip' => 'sometimes|required|string|between:4,5',
'city' => 'sometimes|required|string|between:4,255',
'amount' => 'required|numeric|between:1,'.Config::get('donations.max'),
'type' => 'required|in:oo,monthly',
'provider' => 'sometimes|string|nullable',
'product_id' => 'sometimes|exists:products,id|nullable',
'campaign_id' => 'required|exists:campaigns,id',
'status' => 'sometimes|required|in:pending,canceled,success,error',
'profile' => 'sometimes|string|regex:/^profile[0-9]+$/|nullable',
];
}
/**
* Get the validation attributes that apply to the request.
*
* @return array
*/
public function attributes()
{
return [
//
];
}
/**
* Get the validation messages that apply to the request.
*
* @return array
*/
public function messages()
{
return [
//
];
}
private function prepareForValidation()
{
dd('getValidatorInstance custom');
$this->sanitizeInput();
return parent::getValidatorInstance();
}
private function sanitizeInput()
{
dd('sanitizeInput custom');
$data = $this->all();
dd($data);
// overwrite the newsletter field value to match boolean validation
$data['newsletter'] = ($data['newsletter'] == 'true' || $data['newsletter'] == '1' || $data['newsletter'] == true) ? true : false;
return $data;
}
private function validate() {
dd('validate');
}
}
如您所见,我首先尝试覆盖 getValidatorInstance 方法,因为这看起来像是常见的方法,但它没有被执行(所以没有被覆盖 - 受保护?)。
【问题讨论】:
-
我目前无法测试,但这可能只是一个错字吗?
private function prepareForValidation(),尝试将其更改为公开。 -
不,没有区别...不能覆盖该方法:/ thx!
-
prepareForValidation()是否受到保护并不重要,这是您应该重写以执行这些类型的任务的方法。在此方法中,调用$this->replace()将您的输入替换为经过清理的变体。
标签: php laravel validation laravel-5.4