PHPackages                             umbalaconmeogia/laravel-language-switcher - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Localization &amp; i18n](/categories/localization)
4. /
5. umbalaconmeogia/laravel-language-switcher

ActiveLibrary[Localization &amp; i18n](/categories/localization)

umbalaconmeogia/laravel-language-switcher
=========================================

A simple CSS framework independent Laravel package for language switching

v2.0.0(10mo ago)05MITPHPPHP ^8.1

Since Jul 11Pushed 10mo agoCompare

[ Source](https://github.com/umbalaconmeogia/laravel-language-switcher)[ Packagist](https://packagist.org/packages/umbalaconmeogia/laravel-language-switcher)[ RSS](/packages/umbalaconmeogia-laravel-language-switcher/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (3)Used By (0)

Laravel Language Switcher
=========================

[](#laravel-language-switcher)

A simple, CSS framework independent Laravel package for language switching.

Features
--------

[](#features)

- ✅ **Simple &amp; Lightweight** - No external dependencies
- ✅ **CSS Framework Independent** - Works with any CSS framework
- ✅ **Pure Blade** - No JavaScript required
- ✅ **Easy to Customize** - Simple CSS classes
- ✅ **Session-based** - Remembers language preference

Installation
------------

[](#installation)

```
composer require umbalaconmeogia/laravel-language-switcher
```

Configuration
-------------

[](#configuration)

### Quick Setup

[](#quick-setup)

Publish all assets and configuration:

```
php artisan language-switcher:publish
```

### Selective Publishing

[](#selective-publishing)

Publish only specific assets:

```
# Configuration only
php artisan vendor:publish --provider="Umbalaconmeogia\LanguageSwitcher\LanguageSwitcherServiceProvider" --tag="language-switcher-config"

# Views only
php artisan vendor:publish --provider="Umbalaconmeogia\LanguageSwitcher\LanguageSwitcherServiceProvider" --tag="language-switcher-views"

# CSS assets only
php artisan vendor:publish --provider="Umbalaconmeogia\LanguageSwitcher\LanguageSwitcherServiceProvider" --tag="language-switcher-assets"

# All assets
php artisan vendor:publish --provider="Umbalaconmeogia\LanguageSwitcher\LanguageSwitcherServiceProvider" --tag="language-switcher"
```

Usage
-----

[](#usage)

### 1. Add routes to your `routes/web.php`:

[](#1-add-routes-to-your-routeswebphp)

```
Route::languageSwitcher();
```

### 2. Add the middleware to your application (optional but recommended):

[](#2-add-the-middleware-to-your-application-optional-but-recommended)

In your `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware): void {
    $middleware->web(append: [
        'setlocale',
    ]);
})
```

### 3. Include the language switcher in your views:

[](#3-include-the-language-switcher-in-your-views)

Using the Blade component (recommended):

```

```

Or using the include directive (legacy):

```
@include('language-switcher::language-switcher')
```

### Component Options

[](#component-options)

The Blade component supports a `style` attribute for different style variants:

```

```

**Note**: The language switcher uses a simple, clean design with inline CSS for maximum compatibility. The dropdown appears on hover and works without JavaScript.

### 4. Customize supported languages in `config/language-switcher.php`:

[](#4-customize-supported-languages-in-configlanguage-switcherphp)

```
'supported_languages' => [
    'en' => 'English',
    'ja' => '日本語',
    'vi' => 'Tiếng Việt',
    'fr' => 'Français',
],
'default_language' => 'en',
'fallback_language' => 'en',
'session_key' => 'locale',
'detection_method' => 'all', // 'session', 'url', 'header', 'all'
'url_parameter' => 'locale',
'route_prefix' => false,
'cache' => [
    'enabled' => true,
    'ttl' => 3600,
    'prefix' => 'language_switcher_',
],
'component' => [
    'default_style' => 'default',
    'show_flags' => false,
    'show_language_codes' => false,
    'dropdown_position' => 'bottom-right',
    'animation_duration' => 200,
],
'middleware' => [
    'auto_detect' => true,
    'store_in_session' => true,
    'redirect_on_change' => false,
    'exclude_paths' => ['api/*', 'admin/*'],
],
'api' => [
    'enabled' => true,
    'endpoints' => [
        'current' => '/api/languages/current',
        'supported' => '/api/languages/supported',
        'switch' => '/api/languages/{locale}',
    ],
    'response_format' => 'json',
    'include_metadata' => true,
],
'security' => [
    'csrf_protection' => true,
    'allowed_domains' => [],
    'rate_limiting' => [
        'enabled' => false,
        'max_attempts' => 10,
        'decay_minutes' => 1,
    ],
],
```

Advanced Configuration
----------------------

[](#advanced-configuration)

### Language Detection Methods

[](#language-detection-methods)

The package supports multiple language detection methods:

- **Session**: Uses stored session preference
- **URL**: Uses URL parameter (e.g., `?locale=en`)
- **Header**: Uses Accept-Language header
- **All**: Uses all methods in order (session → URL → header)

### Middleware Features

[](#middleware-features)

- **Path Exclusion**: Skip language detection for specific paths
- **Auto Detection**: Automatic language detection from browser
- **Session Storage**: Store language preference in session
- **Fallback Handling**: Graceful fallback to default language

### Component Configuration

[](#component-configuration)

- **Style Variants**: Default, minimal, compact styles
- **Dropdown Position**: Configurable dropdown positioning
- **Animation**: Customizable animation duration
- **Flags Support**: Optional flag display (future feature)

### Security Features

[](#security-features)

- **CSRF Protection**: Built-in CSRF protection for language switching
- **Rate Limiting**: Configurable rate limiting for API endpoints
- **Domain Restrictions**: Restrict language switching to specific domains

### API Support

[](#api-support)

- **RESTful Endpoints**: Get current language, supported languages
- **JSON Responses**: Standardized API responses
- **Metadata Inclusion**: Optional metadata in API responses

Enhanced Features
-----------------

[](#enhanced-features)

### Console Commands

[](#console-commands)

The package provides several artisan commands for management:

```
# Publish all assets and configuration
php artisan language-switcher:publish

# List supported languages
php artisan language-switcher:list

# List languages in different formats
php artisan language-switcher:list --format=json
php artisan language-switcher:list --format=csv

# Clear language cache
php artisan language-switcher:clear-cache

# Clear cache and session data
php artisan language-switcher:clear-cache --all
```

### API Endpoints

[](#api-endpoints)

When API is enabled, the package provides RESTful endpoints:

```
# Get current language information
GET /api/languages/current

# Get supported languages
GET /api/languages/supported

# Switch language
POST /api/languages/{locale}
```

Example API responses:

```
// GET /api/languages/current
{
    "current_language": "en",
    "current_language_name": "English",
    "timestamp": "2024-01-15T10:30:00.000000Z",
    "metadata": {
        "detection_method": "all",
        "session_key": "locale",
        "default_language": "en",
        "fallback_language": "en"
    }
}

// GET /api/languages/supported
{
    "languages": [
        {
            "code": "en",
            "name": "English",
            "is_default": true,
            "is_fallback": true
        },
        {
            "code": "ja",
            "name": "日本語",
            "is_default": false,
            "is_fallback": false
        }
    ],
    "count": 2,
    "default_language": "en",
    "fallback_language": "en"
}
```

### Event System

[](#event-system)

The package fires events when languages are changed:

```
use Umbalaconmeogia\LanguageSwitcher\Events\LanguageChanged;

// Listen for language changes
Event::listen(LanguageChanged::class, function (LanguageChanged $event) {
    Log::info("Language changed from {$event->previousLanguage} to {$event->newLanguage}");

    // Access user information if available
    if ($event->user) {
        Log::info("Changed by user: {$event->user->email}");
    }
});
```

### Conditional Asset Loading

[](#conditional-asset-loading)

The package automatically loads CSS assets only when needed:

- Assets are not loaded in console commands
- Assets are not loaded for API requests
- Assets can be disabled via configuration

### View Data Sharing

[](#view-data-sharing)

The package automatically shares language data with all views:

```
{{-- Available in all views --}}
Current language: {{ $currentLanguage }}
Supported languages: {{ json_encode($supportedLanguages) }}
```

Language Enum
-------------

[](#language-enum)

The package provides a `Language` enum class for easy language management:

```
use Umbalaconmeogia\LanguageSwitcher\Enums\Language;

// Get supported languages
$languages = Language::getSupportedLanguages();

// Get display name for a language code
$displayName = Language::getDisplayName('ja'); // Returns '日本語'

// Check if language is supported
$isSupported = Language::isSupported('en'); // Returns true

// Get current application locale
$current = Language::getCurrent();

// Get default language
$default = Language::getDefault();

// Check if current language is default
$isDefault = Language::isCurrentDefault();
```

Middleware
----------

[](#middleware)

The package includes a `SetLocale` middleware that automatically sets the application locale based on the user's language preference stored in the session. This middleware:

- Reads the locale from the session (set by the language switcher)
- Validates that the locale is supported
- Falls back to the default language if an unsupported locale is detected
- Sets the application locale using `app()->setLocale()`

### Manual Middleware Registration

[](#manual-middleware-registration)

If you prefer to register the middleware manually, you can add it to your `app/Http/Kernel.php`:

```
protected $middlewareAliases = [
    // ...
    'setlocale' => \Umbalaconmeogia\LanguageSwitcher\Middleware\SetLocale::class,
];
```

Customization
-------------

[](#customization)

- `.language-switcher` - Main container
- `.language-switcher-button` - Button styling
- `.language-switcher-menu` - Dropdown menu
- `.language-switcher-item` - Menu items
- `.language-switcher-item.active` - Active language

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance54

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

305d ago

Major Versions

v1.0.0 → v2.0.02025-07-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/e73262b0c606572246aae623de6388d6f0e2abc6338108f0c96a77b3573983f9?d=identicon)[umbalaconmeogia](/maintainers/umbalaconmeogia)

---

Top Contributors

[![umbalaconmeogia](https://avatars.githubusercontent.com/u/179130?v=4)](https://github.com/umbalaconmeogia "umbalaconmeogia (10 commits)")

---

Tags

laravellocalizationi18nlanguagemultilinguallanguage-switcher

### Embed Badge

![Health badge](/badges/umbalaconmeogia-laravel-language-switcher/health.svg)

```
[![Health](https://phpackages.com/badges/umbalaconmeogia-laravel-language-switcher/health.svg)](https://phpackages.com/packages/umbalaconmeogia-laravel-language-switcher)
```

###  Alternatives

[tractorcow/silverstripe-fluent

Simple localisation for Silverstripe

92421.6k26](/packages/tractorcow-silverstripe-fluent)[pmochine/laravel-tongue

🎉 Finally a subdomain localization that works how you want it to work. 🌐

4158.4k](/packages/pmochine-laravel-tongue)[inpsyde/multilingual-press

Simply THE multisite-based free open source plugin for your multilingual websites.

2414.0k1](/packages/inpsyde-multilingual-press)[jayesh/laravel-gemini-translator

An interactive command to extract and generate Laravel translations using Gemini AI.

691.7k1](/packages/jayesh-laravel-gemini-translator)[alkhatibdev/language-switcher

Laravel dynamic language switcher for web and api routes

124.2k](/packages/alkhatibdev-language-switcher)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
