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

Language Bundle Laravel Package

baconmanager/language-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baconmanager/language-bundle
    

    Add to config/bundles.php (Laravel 5.4+):

    Bacon\Bundle\LanguageBundle\BaconLanguageBundle::class,
    
  2. Route Configuration Add to routes/web.php (or equivalent):

    Route::group([
        'prefix' => '{_locale}',
        'middleware' => ['locale']
    ], function () {
        // Your routes here
    });
    
  3. Middleware Setup Create app/Http/Middleware/LocaleMiddleware.php:

    namespace App\Http\Middleware;
    use Closure;
    use Illuminate\Support\Facades\App;
    
    class LocaleMiddleware
    {
        public function handle($request, Closure $next)
        {
            $locale = $request->segment(1);
            if (in_array($locale, ['en', 'pt', 'es'])) { // Add supported locales
                App::setLocale($locale);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            // ...
            \App\Http\Middleware\LocaleMiddleware::class,
        ],
    ];
    
  4. First Use Case Render the language switcher in a Blade template:

    @languageswitcher(['en', 'pt', 'es']) <!-- Replace with actual template tag if available -->
    

Implementation Patterns

Core Workflows

  1. Locale Routing

    • Use {_locale} in route definitions (e.g., /{_locale}/admin/users).
    • Dynamically set locale via middleware (as shown above).
  2. Translation Integration

    • Store translations in resources/lang/{locale}/messages.php (Laravel convention).
    • Use __() or @lang() in Blade:
      <h1>@lang('messages.welcome')</h1>
      
  3. Language Switcher UI

    • Create a reusable Blade component (resources/views/components/languageswitcher.blade.php):
      @foreach(['en', 'pt', 'es'] as $locale)
          <a href="{{ url()->current() }}" hreflang="{{ $locale }}">
              {{ Str::upper($locale) }}
          </a>
      @endforeach
      
    • Call it in layouts:
      @component('components.languageswitcher') @endcomponent
      
  4. Admin CRUD Integration

    • Extend the bundle’s CRUD routes by adding:
      // routes/web.php
      Route::prefix('{_locale}/admin/languages')->group(function () {
          Route::resource('languages', \Bacon\LanguageController::class);
      });
      
    • Customize the controller to work with Laravel’s Eloquent models.

Advanced Patterns

  • Dynamic Locale Detection Use request headers or user preferences:

    $locale = request()->header('Accept-Language') ?? session('locale') ?? 'en';
    App::setLocale($locale);
    
  • Fallback Locales Configure in app/Providers/AppServiceProvider.php:

    public function boot()
    {
        \Illuminate\Support\Facades\App::setFallbackLocale('en');
    }
    
  • API Localization Return locale-specific responses:

    return response()->json($data, 200, [], null, ['locale' => app()->getLocale()]);
    

Gotchas and Tips

Common Pitfalls

  1. Route Prefix Conflicts

    • Ensure {_locale} doesn’t clash with existing route parameters.
    • Test with php artisan route:list to verify routes.
  2. Middleware Order

    • Place LocaleMiddleware before other middleware that relies on locale (e.g., CORS, auth).
  3. Translation Caching

    • Clear cached views after adding new translations:
      php artisan view:clear
      php artisan config:clear
      
  4. Bundle-Specific Quirks

    • The bundle assumes Symfony2 conventions (e.g., AppKernel.php). Adapt to Laravel’s config/bundles.php.
    • If using the CRUD, ensure your Language model extends Laravel’s Model and not Symfony’s Entity.

Debugging Tips

  • Check Locale Log the current locale in middleware:

    \Log::debug('Current locale:', ['locale' => app()->getLocale()]);
    
  • Route Debugging Use dd(Route::current()->getParameters()) to inspect captured {_locale}.

  • Translation Debugging Verify translations exist in resources/lang/{locale}/messages.php:

    dd(__('messages.key', [], app()->getLocale()));
    

Extension Points

  1. Custom Locale Provider Override the default locale logic by binding a service:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(\Bacon\LocaleProvider::class, function () {
            return new \App\Services\CustomLocaleProvider();
        });
    }
    
  2. Extend Language Switcher Create a custom view component to style the switcher:

    <!-- resources/views/custom/languageswitcher.blade.php -->
    <select onchange="window.location.href=this.value">
        @foreach(config('app.locales') as $locale)
            <option value="{{ url()->current() }}" {{ app()->getLocale() === $locale ? 'selected' : '' }}>
                {{ $locale }}
            </option>
        @endforeach
    </select>
    
  3. Add New Locales Update config/app.php:

    'locales' => ['en', 'pt', 'es', 'fr'],
    

    And create corresponding translation files.

Performance

  • Avoid Over-Fetching Lazy-load translations for non-critical paths:

    if (app()->getLocale() === 'en') {
        // Load English translations only when needed
    }
    
  • Cache Translations Use Laravel’s translation caching:

    php artisan translate:cache
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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