Courses

Multi-Language Laravel 11: All You Need to Know

Translating Validation Messages

Summary of this lesson:
- Use `attributes()` method to customize field names in validation
- Handle array field validations with custom attribute names
- Use `:index` or `:position` placeholders in validation messages
- Implement custom validation messages with `messages()` method
- Improve user-friendly validation error reporting

In Laravel, majority of validation error messages are good enough:

However, if you change the label, the validation message does not match the label:

Let's see how we can fix this.


Label and Field Name Mismatch - Translated Form Attributes

As the application grows, you'll have cases where the field name and label do not match. For example, I have a field called Order Date on the UI but the form has an ordered_at name:

Blade form

<div class="mt-4">
<x-input-label for="ordered_at" :value="__('Order date')"/>
 
<x-text-input id="ordered_at" class="block mt-1 w-full" type="date" name="ordered_at"
:value="old('ordered_at')"/>
 
<x-input-error :messages="$errors->get('ordered_at')" class="mt-2"/>
</div>

This will result in the following validation message:

The ordered at field is required.

It is not that user-friendly as our name is Order date. Let's fix this by adding the attributes method to our Form Request class:

Form Request Class

use Illuminate\Foundation\Http\FormRequest;
 
class StoreOrderRequest extends FormRequest
{
public function rules(): array
{
return [
'ordered_at' => ['required', 'date'],
// ...
];
}
 
// ...
 
public function attributes(): array
{
return [
'ordered_at' => 'order date',
];
}
}

With this, we've told that once we have a field named ordered_at - its visual representation should be order date. This will result in the following validation message:

The order date field is required.

To go even further, we can use a translation here:

Form Request Class

// ...
public function attributes(): array
{
return [
'ordered_at' => __('Order date'),
];
}

This will result in: The Order date field is required. - matching the label.


Validating Array of Fields

This one is tricky. You might see something like...

The full lesson is only for Premium Members.
Want to access all 18 lessons of this course? (80 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord