In a package, I’m trying to have custom validation error messages in a file separated from the default one of Laravel. I’ve duplicated the file, changed the values (did not touch the keys), loaded it correctly in the service provider and everything worked fine. Base validations such as required, numeric, email, etc displayed the text in my file. Now, I tried to use the size rule, but since the error messages are in an array, it gives me this Exception when using $errors->get( 'content.reasons' ):
Array to string conversion in MessageBag.php (line 246)
Here the important parts of the code
Controller
$validator = Validator::make( $request->all(), $rules, trans( 'admin::validation' ) );
if ( $validator->fails() ){
return redirect()
->back()
->withInput()
->withErrors( $validator );
}
$request->all()
[
// ...
"content" => [
"reasons" => [
[...],
[...]
]
],
// ...
]
$rules
[
// ...
"content.reasons" => "required|size:3"
// ...
]
trans( 'admin::validation' )
// Exact structure of Laravel validation.php
[
// ...
'size' => [
'numeric' => 'The field must be :size.',
'file' => 'The field must be :size kilobytes.',
'string' => 'The field must be :size characters.',
'array' => 'The field must contain :size items.',
],
// ...
]
After the redirect
$errors = session()->get('errors') ?: new ViewErrorBag;
$field[ 'errors' ] = $errors->get( $dot_name ); // Exception thrown when $dot_name
// equals `content.reasons`.
$errors
Illuminate\Support\ViewErrorBag {
#bags: array:1 [
"default" => Illuminate\Support\MessageBag {
#messages: array:4 [
"content.why_title" => array:1 [
0 => "The field is required."
]
"content.reasons" => array:1 [
0 => array:4 [
"numeric" => "The field must be 3."
"file" => "The field must be 3 kilobytes."
"string" => "The field must be 3 characters."
"array" => "The field must contain 3 items."
]
]
"content.reasons.0.icon" => array:1 [
0 => "The field is required."
]
"content.reasons.0.text" => array:1 [
0 => "The field is required."
]
]
#format: ":message"
}
]
}
I've tried passing content.reasons.array but it returns an empty array.
I've also tried to pass no messages (use Laravel's defaults) and it works, but I really need custom messages...
TL;DR: How can we pass custom messages with the same schema as Laravel?
echoanarraysize). Hope it clarifies the question.'size' => 'The field must be :size.', but with this way, I have to say goodbye to other types.