I'm using a Livewire component to upload a file. Of course, I do some validation when the file is uploaded. But before my validationlogic is triggered, Livewire does some default validation out of the box. (See https://laravel-livewire.com/docs/2.x/file-uploads#global-validation)
This default validator is triggered when a file is larger than 12mb. Since this is the 'max' rule, Laravel's default message is used:
'file' => 'The :attribute must not be greater than :max kilobytes.',
I have a problem with the :attribute
part. Normally you can set some defaults in various translation files. But that does not seem to work in this case. When the validation fails, the attribute is set to the livewire attributename that is currently failing:
When I check the response of the uploaded file, I see this:
{"message":"Files.0 mag niet meer dan 12288 kilobytes zijn.","errors":{"files.0":["Files.0 mag niet meer dan 12288 kilobytes zijn."]}}
I want to customize the 'profileImage' part. I've tried to set this in the component, without results:
protected $validationAttributes = [
'profileImage' => 'Profile image'
];
I think that Files.0
automatically is replaced with the livewire attribute name. That is, of course, very nice of Livewire. But customizing seems to be impossible...
Can anybody help me out here?
Well, after some searching with a colleague, we have found an answer to the question. It doesn't work out of the box unfortunately.
The replacement logic happens in the uploadErrored
method on the trait Livewire\WithFileUploads
, where the Laravel error with starts with the key 'files.0' gets replaced with the Livewire attribute name 'profileImage'.
$errorsInJson = $isMultiple
? str_ireplace('files', $name, $errorsInJson)
: str_ireplace('files.0', $name, $errorsInJson);
$errors = json_decode($errorsInJson, true)['errors'];
throw (ValidationException::withMessages($errors));
We have made an own implementation of the WithFileUploads trait, where we push the attributes name through the translator manually.
$errors = json_decode($errorsInJson, true)['errors'];
$errors = collect($errors)
->mapWithKeys(function (array $values, string $key) use ($isMultiple, $name, $attribute) {
$fieldName = $isMultiple ? 'files' : 'files.0';
$key = str_ireplace($fieldName, $name, $key);
$values = array_map(function ($value) use ($fieldName, $attribute) {
$value = str_replace($fieldName, ':name', $value);
$value = str_replace(ucfirst($fieldName), ':Name', $value);
return trans($value, ['name' => $attribute]);
}, $values);
return [$key => $values];
})
->toArray();
throw (ValidationException::withMessages($errors));