我需要创建一个Laravel自定义请求。但当我这样做时,验证会立即触发。我不知道为什么。这是我的代码:
// this is in my ProjectController class. When a project gets created, i want the customer contact to be saved with it.
public function store(StoreProjectRequest $request)
{
//dd($request->only('contact')['contact']);
$storeContactReq = app()->make(\App\Http\Requests\StoreContactRequest::class);
//the validation gets triggered right here, before i have the chance to add my request data
// even if i dd() here, i dont even reach this line of code
$storeContactReq->request->add($request->only('contact')['contact']); //yes this is correct
$storeContactReq->setMethod('POST');
$cc = new ContactController();
$con = $cc->store($storeContactReq);
dd($con);
//....
}
下面是我的StoreContact请求:
class StoreContactRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
//later
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
"lastname" => 'required',
"firstname" => 'required',
"email" => 'required|email',
"phone" => 'required',
"street" => 'required',
"house" => 'required',
"postcode" => 'required',
"city" => 'required',
];
}
public function messages()
{
return [
'firstname.required' => 'Vorname ist leer',
'lastname.required' => 'Nachname ist leer',
'street.required' => 'Straße ist leer',
'house.required' => 'Hausnummer ist leer',
'postcode.required' => 'Postleitzahl ist leer',
'city.required' => 'Ort ist leer',
'phone.required' => 'Telefon ist leer',
'email.required' => 'Email ist leer',
'email.email' => 'Email ist keine korrekte Mailadresse'
];
}
public function failedValidation(Validator $validator)
{
dd($validator->errors());
}
错误消息:
Illuminate\Support\MessageBag^ {#1359 // app/Http/Requests/StoreContactRequest.php:56
#messages: array:8 [
"lastname" => array:1 [
0 => "Nachname ist leer"
]
"firstname" => array:1 [
0 => "Vorname ist leer"
]
"email" => array:1 [
0 => "Email ist leer"
]
"phone" => array:1 [
0 => "Telefon ist leer"
]
"street" => array:1 [
0 => "Straße ist leer"
]
"house" => array:1 [
0 => "Hausnummer ist leer"
]
"postcode" => array:1 [
0 => "Postleitzahl ist leer"
]
"city" => array:1 [
0 => "Ort ist leer"
]
]
#format: ":message"
}
我在谷歌上搜索了很多,查看了文档,但我就是找不到任何关于这个问题的东西。
我希望在ContactController::store()函数内部触发验证,而不是在手动创建StoreContactRequest时和向其中添加任何数据之前触发验证......
thx
2条答案
按热度按时间ecfsfe2w1#
数据已存在于请求中。您可以使用Request对其进行验证。如有必要,您可以在StoreContactRequest rules()方法中手动添加自定义数据,甚至可以创建自定义验证规则:https://laravel.com/docs/9.x/validation#custom-validation-rules
lqfhib0f2#
我通过在store()方法中添加本地验证器来解决这个问题
这不是很方便,我想我会得到问题与auth在这里,但现在它的工作。Thx所有