I have a FormRequest
with the withValidator()
method (which I copied exactly as it is in the Laravel documentation), but when executing the class an error is returned.
Class:
<?php
namespace App\Http\Requests\Conversation;
use Illuminate\Foundation\Http\FormRequest;
class StoreConversationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'type' => 'required|in:text,media',
'text' => 'required_if:type,text|string',
'medias' => 'required_if:type,media|array',
'medias.*' => 'file|max:5120|mimes:jpg,jpeg,png,pdf,mp3,mp4',
'phone' => 'required|numeric',
'conversation' => 'required|exists:conversations,id',
];
}
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
}
Error:
Method App\Http\Requests\Conversation\StoreConversationRequest::somethingElseIsInvalid does not exist.
I tried replacing $this
with $validator
but the error persists:
Method Illuminate\Validation\Validator::somethingElseIsInvalid does not exist.
CodePudding user response:
I quite didn't get from where did you find this function:
somethingElseIsInvalid()
Try In this way:
public function withValidator( $validator )
{
if ( $validator->fails() ) {
// Handle errors
}
...
}
CodePudding user response:
I solved problem with this:
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($validator->errors()->isNotEmpty()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
But I don't understand why a code in the documentation is not working.