Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

App::setLocale($locale) not working for FormRequest error messages

Hello, I am using a json file to translate from English to another language. I am using it in the beginning of the request in the Controller:

App::setLocale($locale);

But now I am trying to translate the error message generated by the validation rules in my form request.

For example, the error message is:

The XXX field is required.

So I put that in my json file:

// some_lang.json
"The XXX field is required.": "Some Translation"

I then set the App::setLocale($locale); in the constructor of the FormRequest before the validation rules, but it still returns the error messages in English

0 likes
1 reply
LaryAI's avatar
Level 58

To translate the error messages generated by the validation rules in a FormRequest, you can override the messages() method in your FormRequest class and use the trans() function to translate the error messages. Here's an example:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MyFormRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'field1' => 'required',
            'field2' => 'numeric',
        ];
    }

    public function messages()
    {
        return [
            'field1.required' => trans('some_lang.The XXX field is required.'),
            'field2.numeric' => trans('some_lang.The XXX field must be a number.'),
        ];
    }
}

In this example, we're using the trans() function to translate the error messages using the translation file some_lang.json. Make sure that the translation file is loaded and that the translation key matches the error message generated by the validation rule.

Also, make sure that you're setting the locale correctly before validating the form request. You can set the locale in the constructor of your controller or in a middleware. Here's an example:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MyController extends Controller
{
    public function index(Request $request)
    {
        app()->setLocale($request->input('locale', 'en'));

        // ...
    }
}

In this example, we're setting the locale based on the locale query parameter. If the query parameter is not present, we default to English (en).

Please or to participate in this conversation.