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 Laravel Package

beloop/language

Laravel package for handling application languages and localization: manage available languages, switch the current locale, and provide helpers/middleware for language detection and routing. Lightweight setup for multilingual sites and dashboards.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require beloop/language
    

    (Note: Due to the package being archived, verify compatibility with your Laravel version—likely PHP 7.2+ and Laravel 5.x/6.x.)

  2. Basic Usage The package provides a Language facade for managing multilingual content. Initialize it in a service provider:

    use Beloop\Language\Facades\Language;
    
    // Set default language
    Language::setDefault('en');
    
    // Load translations (if using a custom loader)
    Language::loadTranslations(['en' => 'en.json', 'fr' => 'fr.json']);
    
  3. First Use Case: Dynamic Language Switching

    // In a controller/middleware
    $currentLang = Language::getCurrent();
    $translatedText = Language::get('key.subkey', [], $currentLang);
    

Implementation Patterns

Core Workflows

  1. Language Detection & Switching

    • Automatic Detection: Use middleware to detect user preference (e.g., from Accept-Language header or session):
      public function handle($request, Closure $next) {
          $lang = $request->header('Accept-Language') ?? session('lang');
          Language::setCurrent($lang);
          return $next($request);
      }
      
    • Manual Override: Allow users to switch languages via a dropdown:
      // Route
      Route::get('/lang/{lang}', function ($lang) {
          Language::setCurrent($lang);
          return redirect()->back();
      });
      
  2. Translation Management

    • Custom Loaders: Extend Beloop\Language\Loaders\LoaderInterface to fetch translations from a database or API:
      class DatabaseLoader implements LoaderInterface {
          public function load($locale) {
              return DB::table('translations')->where('locale', $locale)->get();
          }
      }
      
    • Fallback Chain: Configure fallback languages in config/language.php:
      'fallbacks' => [
          'fr' => ['en'],
          'es' => ['en'],
      ],
      
  3. Integration with Laravel Ecosystem

    • Localization Middleware: Combine with Laravel’s built-in localization:
      public function __construct() {
          $this->middleware(function ($request, $next) {
              app()->setLocale(Language::getCurrent());
              return $next($request);
          });
      }
      
    • Blade Directives: Create a custom directive for translations:
      Blade::directive('lang', function ($expression) {
          return "<?php echo \Beloop\Language\Facades\Language::get({$expression}); ?>";
      });
      
      Usage:
      @lang('key.subkey')
      
  4. API Responses

    • Dynamically set Accept-Language header in API responses:
      return response()->json($data)
          ->header('Content-Language', Language::getCurrent());
      

Gotchas and Tips

Pitfalls

  1. Archived Package Risks

    • No Updates: The last release is from 2019. Test thoroughly for PHP 8.x/Laravel 8+ compatibility.
    • Security: Manually audit for vulnerabilities (e.g., unsafe eval() in dynamic translation loading).
    • Forking: Consider forking the repo to maintain it if critical to your project.
  2. Performance

    • Translation Caching: Implement a cache layer for translations (e.g., Redis) to avoid repeated DB/API calls:
      Cache::remember("lang.{$locale}", 3600, function () use ($locale) {
          return Language::loadTranslations([$locale => 'path']);
      });
      
    • Avoid Over-Fetching: Load only necessary locales/translations.
  3. Edge Cases

    • Invalid Locale Handling: Validate locales early to avoid runtime errors:
      if (!Language::hasLocale($locale)) {
          abort(400, 'Unsupported language');
      }
      
    • Right-to-Left (RTL) Languages: Ensure your UI framework (e.g., Bootstrap) supports RTL for languages like Arabic/Hebrew.
  4. Debugging

    • Translation Keys: Use Language::getAvailableLocales() and Language::getAvailableKeys() to inspect loaded data.
    • Fallback Logic: Debug why a translation might fall back unexpectedly by checking the fallbacks config and loaded data.

Tips

  1. Configuration

    • Centralize language settings in config/language.php:
      return [
          'default' => 'en',
          'supported' => ['en', 'fr', 'es'],
          'loader' => \Beloop\Language\Loaders\JsonLoader::class,
      ];
      
  2. Testing

    • Mock the Language facade in tests:
      $this->app->instance('Beloop\Language\Facades\Language', $mockLanguage);
      
    • Test fallback chains and edge cases (e.g., unsupported locales).
  3. Extending Functionality

    • Custom Translation Sources: Add support for Markdown/HTML translations by extending the loader.
    • User Preferences: Store preferred language in the user model:
      class User extends Authenticatable {
          public function setLanguage($lang) {
              $this->language = $lang;
              Language::setCurrent($lang);
              $this->save();
          }
      }
      
  4. Internationalization (i18n) Beyond Translations

    • Use the package as part of a broader i18n strategy (e.g., number/date formatting via Carbon or laravel-i18n).
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity