< BACK TO BLOG

Translating form fields in Laravel

Published May 11, 2022

When using a language other than english, it can be pretty confusing when a form/api returns a validation error, because by default it will use the names of the attributes in the form itself, so it will look quite jarring.

For example if i have an email field with the required rule, and it fails in Arabic, here's what I would get:

{
   "errors": {
      "email": ["الحقل email مطلوب"]
   }
}

it might work, but it won't correspond to what the user is seeing on their screen.

Luckily this is a pretty easy fix.

with any Laravel project, in the lang directory for each language, there should exist a file called validation.php, if this file doesn't exist for your target language, then go ahead and create it, if you're on linux you can easily use touch lang/ar/validation.php to create it from terminal.

the validation.php file contains translations for all validation rules by default, and it should also contain an empty array called attributes, if it doesn't go ahead and add it.

The attributes array is a key value pair that will be used, so if you have a field called email, then you'd add a key email and the value corresponds to the translation of that attribute, here's an example

// lang/translation/ar/validation.php

return [
   // rule translations
   'attributes' => [
      'email' => 'البريد الإلكتروني',
      'user.email' => 'البريد الإلكتروني',
   ]
];

as you can see, we can simply map the field name to its translation, and one nice use case is that if you're expecting different objects in a request, you can just use the path to that attribute in the json using the dot notation and it will work as expected.

so in the previous example, the new validation response should look something like this:

{
   "errors": {
      "email": ["حقل البريد الإلكتروني مطلوب"]
   }
}

You can even use these translations to convert a technical input name to a more human readable name for better UX.