PHPackages                             jeffersongoncalves/laravel-locale-cookie - 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. jeffersongoncalves/laravel-locale-cookie

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

jeffersongoncalves/laravel-locale-cookie
========================================

A Laravel middleware that resolves the application locale from a cookie, validating the requested value against a configurable list of supported locales and falling back to a sensible default when the cookie is missing or unknown. Cookie name, supported locales, and fallback locale are all driven by config.

v1.3.0(1mo ago)154MITPHPPHP ^8.2CI passing

Since Jun 20Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/jeffersongoncalves/laravel-locale-cookie)[ Packagist](https://packagist.org/packages/jeffersongoncalves/laravel-locale-cookie)[ Docs](https://github.com/jeffersongoncalves/laravel-locale-cookie)[ GitHub Sponsors](https://github.com/jeffersongoncalves)[ RSS](/packages/jeffersongoncalves-laravel-locale-cookie/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (5)Dependencies (6)Versions (7)Used By (0)

[![Laravel Locale Cookie](https://raw.githubusercontent.com/jeffersongoncalves/laravel-locale-cookie/master/art/jeffersongoncalves-laravel-locale-cookie.png)](https://raw.githubusercontent.com/jeffersongoncalves/laravel-locale-cookie/master/art/jeffersongoncalves-laravel-locale-cookie.png)

Laravel Locale Cookie
=====================

[](#laravel-locale-cookie)

[![Latest Version on Packagist](https://camo.githubusercontent.com/62ac042389d2439279a76e7a1ccf7c5e42b2f0f96098d629a468a480af54bf33/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d6c6f63616c652d636f6f6b69652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jeffersongoncalves/laravel-locale-cookie)[![GitHub Tests Action Status](https://camo.githubusercontent.com/e37318f0ccf12b18175ba18a45223322328c9ddc1a1c6b0dbfa9f9ddeb98fff4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d6c6f63616c652d636f6f6b69652f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/jeffersongoncalves/laravel-locale-cookie/actions?query=workflow%3Arun-tests+branch%3Amaster)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/d9e063ffd98d3a5e668f13d3381fca6cf899c62b59b14065665d5e743bc654dc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d6c6f63616c652d636f6f6b69652f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d6173746572266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/jeffersongoncalves/laravel-locale-cookie/actions?query=workflow%3A%22Fix+PHP+code+styling%22+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/8be5ea77e62ecdac0f6f6e8de1c887f025c693facb6680a810a92a6dc153b624/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d6c6f63616c652d636f6f6b69652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jeffersongoncalves/laravel-locale-cookie)

A Laravel middleware that resolves the application locale from a cookie. The requested value is validated against a configurable list of supported locales and ignored when it is missing or unknown, falling back to a sensible default. Cookie name, supported locales, and fallback locale are all driven by config.

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

[](#installation)

You can install the package via composer:

```
composer require jeffersongoncalves/laravel-locale-cookie
```

You can publish the config file with:

```
php artisan vendor:publish --tag="locale-cookie-config"
```

This is the contents of the published config file:

```
return [
    'cookie' => 'locale',
    'supported' => ['en'],
    'fallback' => null,
];
```

- `cookie` — the name of the cookie the middleware reads the visitor's locale from (default `locale`).
- `supported` — the whitelist of accepted locales. A cookie value that is not in this list is ignored.
- `fallback` — the locale applied when the cookie is missing or unsupported. When `null`, the middleware falls back to the framework's `config('app.fallback_locale')`.

Usage
-----

[](#usage)

Register the middleware on the route group that should be locale-aware. The middleware reads the cookie, validates it against your `supported` list, and applies the matching locale (or the fallback) for the rest of the request:

```
use JeffersonGoncalves\LocaleCookie\Middleware\SetLocale;

Route::middleware(SetLocale::class)->group(function () {
    // ...locale-aware routes
});
```

For convenience, the package also registers a `locale` middleware alias, so you can reference it by name:

```
Route::middleware('locale')->group(function () {
    // ...locale-aware routes
});
```

You can also alias it in `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \JeffersonGoncalves\LocaleCookie\Middleware\SetLocale::class,
    ]);
})
```

### Setting the cookie

[](#setting-the-cookie)

This package only **reads** the locale cookie — it never writes it. Your application is responsible for setting the cookie when the visitor chooses a locale. You can do that from PHP:

```
return redirect()->back()->withCookie(cookie()->forever('locale', 'pt_BR'));
```

…or from the client with JavaScript:

```
document.cookie = 'locale=pt_BR; path=/; max-age=31536000';
```

### Encrypted cookies

[](#encrypted-cookies)

By default Laravel's `EncryptCookies` middleware encrypts every cookie, and it runs **before** this middleware. To keep the read side (the `SetLocale` middleware, which reads the raw value via `$request->cookies->get()`) and the write side (the bundled switch route) consistent — and so that **client-set** cookies (e.g. the JavaScript example above, which are never encrypted) keep working — **the package automatically registers the configured cookie name in `EncryptCookies`' exception list** (via `EncryptCookies::except()`). The cookie is therefore always written and read as a plaintext value; you do not need to add it to `$except` yourself.

If you change `locale-cookie.cookie`, the exclusion follows the new name automatically.

### Using with Livewire

[](#using-with-livewire)

If your locale-aware pages use Livewire, register the middleware as a Livewire persistent middleware as well, so subsequent `/livewire/update` requests keep the visitor's locale instead of falling back to the default. Register both the route-group middleware **and** the persistent middleware (pattern taken from the source project this package was extracted from):

```
use Livewire\Livewire;
use JeffersonGoncalves\LocaleCookie\Middleware\SetLocale;

// In a service provider's boot() method
Livewire::addPersistentMiddleware([
    SetLocale::class,
]);
```

### Locale switch route

[](#locale-switch-route)

The package registers a ready-made route that persists the chosen locale in the cookie and redirects back to a same-host Referer (open-redirect safe). Point your language switcher at it:

```
@foreach (config('locale-cookie.supported') as $code)
    {{ strtoupper($code) }}
@endforeach
```

The `{locale}` param is constrained to `config('locale-cookie.supported')`. Configure (or disable) it under `locale-cookie.switch`:

```
'switch' => [
    'enabled' => true,
    'path' => 'locale/{locale}',
    'name' => 'locale.switch',
    'lifetime' => 60 * 24 * 365, // cookie lifetime in minutes
    'middleware' => ['web'],     // attaches the queued cookie; the locale cookie is excluded from encryption
],
```

### Shortening a locale code

[](#shortening-a-locale-code)

The `LocaleCookie::short()` helper reduces a locale to its short language code — handy for ``, flag icons, or any place you only need the base language:

```
use JeffersonGoncalves\LocaleCookie\LocaleCookie;

LocaleCookie::short('pt_BR'); // 'pt'
LocaleCookie::short('pt-BR'); // 'pt'
LocaleCookie::short('EN');    // 'en'
LocaleCookie::short();        // current app locale, shortened
LocaleCookie::short('');      // 'en' (fallback when there is no usable prefix)
```

```

```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Jèfferson Gonçalves](https://github.com/jeffersongoncalves)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance91

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.3% 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

5

Last Release

44d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/411493?v=4)[Jefferson Gonçalves](/maintainers/jeffersongoncalves)[@jeffersongoncalves](https://github.com/jeffersongoncalves)

---

Top Contributors

[![jeffersongoncalves](https://avatars.githubusercontent.com/u/411493?v=4)](https://github.com/jeffersongoncalves "jeffersongoncalves (12 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

composeri18njeffersongoncalveslaravellaravel-packagelocalelocalizationmiddlewarephplaraveljeffersongoncalveslaravel-locale-cookie

###  Code Quality

TestsPest

Static AnalysisPHPStan

### Embed Badge

![Health badge](/badges/jeffersongoncalves-laravel-locale-cookie/health.svg)

```
[![Health](https://phpackages.com/badges/jeffersongoncalves-laravel-locale-cookie/health.svg)](https://phpackages.com/packages/jeffersongoncalves-laravel-locale-cookie)
```

###  Alternatives

[spatie/laravel-medialibrary

Associate files with Eloquent models

6.2k45.4M679](/packages/spatie-laravel-medialibrary)[spatie/laravel-health

Monitor the health of a Laravel application

88212.7M180](/packages/spatie-laravel-health)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

24773.9k](/packages/harris21-laravel-fuse)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

817336.8k3](/packages/defstudio-telegraph)[nativephp/mobile

NativePHP for Mobile

1.1k102.1k123](/packages/nativephp-mobile)[keepsuit/laravel-opentelemetry

OpenTelemetry integration for laravel

168666.7k1](/packages/keepsuit-laravel-opentelemetry)

PHPackages © 2026

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