After reading the docs, I've understood the strucutre in resources/lang/xx/validation.php
to add custom error messages.
'custom' => [
'name' => [
'required' => 'Please fill the name of the company'
]
],
My problem here is that after setting this up, I won't be able to use a field called name
to another resource, for instance a Please fill out your name
message. When overriding the method messages()
inside the FormRequest, I'm able to be more specific in these messages, but then I lose the Language
customization.
My question is: How can I go about setting up custom messages for different Form Requests and still keep the language system working in my favor?
Edit
To better explain what I want, here is a little bit of code.
class CompanyRequest extends Request {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'name' => 'required|max:20'
];
}
public function messages() {
// Here I have specific message for Company name field, but I'm
// stuck with one single language.
return [
'name.required' => 'Can you please fill the company name.',
'name.max' => 'The name of the company cannot be bigger than 20 characters'
];
}
}
Now the UserRequest
class UserRequest extends Request {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'name' => 'required|max:40',
'email' => 'required|email'
];
}
public function messages() {
// Here I have specific message for User name field, but I'm stuck
// with one single language.
return [
'name.required' => 'Please provide your full name',
'name.max' => 'If your name is bigger than 40 characters, consider using only first and last name.'
];
}
}
Now, this works perfectly, but I'm stuck with English. I can solve that with the resources/lang/en/validation.php
file. Now, I'll erase the messages
method and use the validation file instead.
'custom' => [
// Here I can have multiple validation files for different languages,
// but how would I go about to define the field name for other entities
// (such as the user message).
'name' => [
'required' => 'Please fill the name of the company',
'max' => 'The field cannot have more than 20 characters',
]
]
Now, how can I differ the messages for the field name
for Company entity and the field name
for User entity?
To wrap it up:
- The Form Request provides me a way of overriding a messages() method that allow me to use the term
name
for multiple forms. - The Validation file provides me a way of using multiple languages (I can create a
resources/lang/fr/validation.php
, but I can only define the field "name" once. I cannot have different messages for a field name.