Courses

Multi-Language Laravel 11: All You Need to Know

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...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 68 courses (1188 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord