You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6多语言验证:切换错误消息语言环境

Got it, let's tackle this validation message locale issue in your Laravel setup. Here's how you can make sure validation errors show up in the right language, even when submitting the contact form:

Key Problem to Fix

Your GET route includes the {locale} parameter to set the language, but the POST route doesn't carry this value. When the form submits and triggers validation, the app falls back to the default English locale because it can't detect the user's current language context. We'll fix this by explicitly setting the locale in your ContactFormRequest.


This is the most reliable approach since it persists the user's language choice across their session.

  1. Save the locale to the session when loading the contact form
    Update your ContactController@create method to store the active locale:

    // ContactController.php
    use Illuminate\Support\Facades\App;
    
    public function create($locale)
    {
        App::setLocale($locale);
        session()->put('active_locale', $locale); // Persist locale to session
        return view('contact');
    }
    
  2. Set locale from session in your Form Request
    Add a prepareForValidation method to your ContactFormRequest to pull the locale from the session before validation runs:

    // ContactFormRequest.php
    use Illuminate\Support\Facades\App;
    
    protected function prepareForValidation()
    {
        // Use the stored locale if it exists, default to English otherwise
        if ($locale = session()->get('active_locale')) {
            App::setLocale($locale);
        }
    }
    

Option 2: Pass Locale via Hidden Form Field

If you don't want to use sessions, you can embed the current locale directly in the form as a hidden input.

  1. Add a hidden locale field to your contact form
    In your contact.blade.php view, add this field inside the form:

    <form method="POST" action="{{ route('contact.store') }}">
        @csrf
        <input type="hidden" name="locale" value="{{ App::getLocale() }}">
        <!-- Your other form fields go here -->
    </form>
    
  2. Validate and set the locale in the Form Request
    Update your ContactFormRequest to read the locale from the request and apply it:

    // ContactFormRequest.php
    use Illuminate\Support\Facades\App;
    
    protected function prepareForValidation()
    {
        // Define your supported locales to prevent invalid values
        $allowedLocales = ['en', 'zh', 'fr']; // Adjust to your app's languages
        $locale = $this->input('locale', 'en');
    
        if (in_array($locale, $allowedLocales)) {
            App::setLocale($locale);
        }
    }
    
    public function rules()
    {
        return [
            'locale' => 'nullable|in:en,zh,fr', // Match your allowed locales
            // Your other validation rules
        ];
    }
    

Option 3: Parse Locale from Referrer URL

If you can't modify the form or session, you can extract the locale from the referrer URL (the page the user came from).

Add this to your ContactFormRequest:

// ContactFormRequest.php
use Illuminate\Support\Facades\App;

protected function prepareForValidation()
{
    $referrer = $this->headers->get('referer');
    if ($referrer) {
        // Split the referrer path to get the locale segment
        $pathSegments = explode('/', trim(parse_url($referrer, PHP_URL_PATH), '/'));
        $allowedLocales = ['en', 'zh', 'fr'];

        if (isset($pathSegments[0]) && in_array($pathSegments[0], $allowedLocales)) {
            App::setLocale($pathSegments[0]);
        }
    }
}

Note: This relies on the referrer header, which isn't always guaranteed to be present, so use this as a last resort.


Important Final Check

Make sure you've created the validation language files for each locale in resources/lang/{locale}/validation.php with all the translated error messages you need. Without these files, Laravel will still fall back to English.

内容的提问来源于stack exchange,提问作者trojan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:23:49