Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel View Localization Laravel Package

vxm/laravel-view-localization

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require vxm/laravel-view-localization
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Vxm\ViewLocalization\ViewLocalizationServiceProvider"
    
  2. Basic Usage: Define locale-specific views in resources/views/{locale}/ (e.g., resources/views/en/, resources/views/vi/). Example structure:

    resources/
    ├── views/
    │   ├── en/
    │   │   └── welcome.blade.php
    │   └── vi/
    │       └── welcome.blade.php
    
  3. First Use Case: Render a view dynamically based on the user's locale:

    // In a controller or route closure
    return view('welcome'); // Automatically resolves to `en/welcome.blade.php` or `vi/welcome.blade.php`
    
  4. Locale Detection: Ensure your app detects the user's locale (e.g., via middleware or AppServiceProvider):

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        $locale = session('locale') ?? app()->getLocale();
        app()->setLocale($locale);
    }
    

Implementation Patterns

Core Workflows

  1. Locale-Aware View Resolution:

    • The package extends Laravel's view resolver to check for locale-specific files first.
    • Example: view('home') will look for: resources/views/{locale}/home.blade.phpresources/views/home.blade.php.
  2. Fallback Logic:

    • If a locale-specific view doesn’t exist, it falls back to the default view.
    • Customize fallback behavior in config/view-localization.php:
      'fallback_locale' => 'en',
      'fallback_to_default' => true,
      
  3. Dynamic Locale Switching:

    • Change the locale mid-request (e.g., for admin overrides):
      app()->setLocale('vi');
      return view('welcome'); // Now renders `vi/welcome.blade.php`
      
  4. Partial Localization:

    • Localize only specific sections of a view using @localize directives:
      @localize('vi')
          {{ __('vi.some.key') }}
      @endlocalize
      
  5. Integration with Middleware:

    • Set the locale in middleware (e.g., based on user preferences or headers):
      public function handle($request, Closure $next)
      {
          $locale = $request->header('Accept-Language') ?? 'en';
          app()->setLocale($locale);
          return $next($request);
      }
      
  6. Testing:

    • Mock the locale in tests:
      $this->app->setLocale('vi');
      $this->get('/')->assertViewIs('welcome');
      

Advanced Patterns

  1. Locale-Specific Assets:

    • Pair with laravel-mix or vite to load locale-specific JS/CSS:
      // resources/js/app.js
      const locale = document.querySelector('html').getAttribute('lang');
      import(`./locales/${locale}.js`);
      
  2. Fluent API for Chaining:

    • Combine with other view helpers:
      return view('dashboard')
          ->with('user', $user)
          ->locale('vi'); // Override locale for this view only
      
  3. Caching:

    • Cache locale-specific views in production:
      View::addNamespace('locale', resource_path('views'));
      View::addLocation(public_path('views_cache'));
      
  4. API Responses:

    • Useful for localized API responses (e.g., error messages):
      return response()->json(['error' => __('errors.something')], 400);
      

Gotchas and Tips

Pitfalls

  1. View File Naming:

    • Gotcha: Forgetting to include the .blade.php extension in the view name. Fix: Always use view('path.to.view') with extensions omitted (Laravel handles it).
    • Gotcha: Overwriting default views in the root resources/views/ directory. Fix: Keep default views separate and use fallback_locale in config.
  2. Locale Detection Race Conditions:

    • Gotcha: Locale set too late in the request lifecycle (e.g., after view resolution). Fix: Set the locale in middleware before the HandleIncomingRequest middleware.
  3. Caching Issues:

    • Gotcha: Stale cached views when locales change. Fix: Clear the view cache after adding new locale-specific views:
      php artisan view:clear
      
  4. Namespace Conflicts:

    • Gotcha: Using the same view name in multiple locales (e.g., en/home and vi/home). Fix: Ensure unique filenames or use subdirectories (e.g., en/dashboard/home).
  5. Translation Overrides:

    • Gotcha: @localize directives not working as expected. Fix: Ensure the directive is placed outside of @include blocks and that the locale is set before rendering.

Debugging Tips

  1. Check Resolved Locale:

    dd(app()->getLocale()); // Debug current locale
    
  2. View Resolution Logs: Enable debug mode to see which view files are being resolved:

    View::addNamespace('debug', function ($view) {
        \Log::debug("Resolving view: $view");
        return $view;
    });
    
  3. Fallback Behavior:

    • Temporarily disable fallback to test locale-specific views:
      config(['view-localization.fallback_to_default' => false]);
      
  4. File Permissions:

    • Ensure storage/framework/views is writable for caching:
      chmod -R 775 storage/
      

Extension Points

  1. Custom View Locations:

    • Add additional view paths in config/view-localization.php:
      'paths' => [
          resource_path('views/{locale}'),
          resource_path('views/custom/{locale}'),
      ],
      
  2. Locale Providers:

    • Extend locale detection by implementing Vxm\ViewLocalization\Contracts\LocaleProvider:
      use Vxm\ViewLocalization\Contracts\LocaleProvider;
      
      class SessionLocaleProvider implements LocaleProvider
      {
          public function getLocale()
          {
              return session('locale', app()->getLocale());
          }
      }
      
      Register in AppServiceProvider:
      ViewLocalization::extend('session', function () {
          return new SessionLocaleProvider();
      });
      
  3. Event Listeners:

    • Listen for view.localized events to log or modify locale-specific views:
      View::listen('localized', function ($view, $locale) {
          \Log::info("View $view localized to $locale");
      });
      
  4. Blade Directives:

    • Extend @localize with custom logic:
      Blade::directive('localize', function ($locale) {
          return "<?php echo app()->setLocale($locale); ?>";
      });
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle