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