PHPackages                             rawnoq/laravel-locale-detector - 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. rawnoq/laravel-locale-detector

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

rawnoq/laravel-locale-detector
==============================

A Laravel package for automatic locale detection and translation key extraction

1.0.1(6mo ago)066MITPHPPHP ^8.2

Since Nov 12Pushed 6mo agoCompare

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

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

Laravel Locale Detector
=======================

[](#laravel-locale-detector)

A professional Laravel package for automatic locale detection from HTTP headers and translation key extraction from your codebase.

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [Translation Key Extraction](#translation-key-extraction)
- [Translatable Models](#-translatable-models)
- [Advanced Usage](#advanced-usage)
- [Testing](#testing)
- [License](#license)

✨ Features
----------

[](#-features)

- ✅ **Automatic Locale Detection** - Automatically detects user's preferred language from `Accept-Language` header
- ✅ **Translation Key Extraction** - Extract all translation keys from your codebase
- ✅ **Multiple Detection Methods** - Supports Laravel's `getPreferredLanguage()` and direct header parsing
- ✅ **Configurable Supported Locales** - Define which locales your application supports
- ✅ **Global Middleware** - Automatically registered middleware for seamless integration
- ✅ **Multiple Output Formats** - Export translation keys as JSON, PHP, or array format
- ✅ **Namespace Filtering** - Filter translation keys by namespace
- ✅ **Exclude Paths** - Exclude specific directories from key extraction
- ✅ **Translation Key Synchronization** - Sync translation keys to language files automatically
- ✅ **40+ Language Files** - Includes translation files for auth, pagination, passwords, and validation in 40+ languages
- ✅ **Translatable Models** - Wrapper for Astrotomic Translatable with additional helper methods
- ✅ **Database Migrations** - Helper traits and classes for creating translation tables
- ✅ **Translation Format Converter** - Convert between attribute-based and locale-based translation formats

📦 Requirements
--------------

[](#-requirements)

- PHP 8.2 or higher
- Laravel 11.0+ or Laravel 12.0+

🚀 Installation
--------------

[](#-installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require rawnoq/laravel-locale-detector
```

The package will be automatically discovered and registered by Laravel.

### Step 2: Publish Configuration (Optional)

[](#step-2-publish-configuration-optional)

```
php artisan vendor:publish --tag=locale-detector-config
```

This will publish the configuration file to `config/locale-detector.php`.

### Step 3: Publish Language Files (Optional)

[](#step-3-publish-language-files-optional)

```
php artisan vendor:publish --tag=locale-detector-lang
```

This will publish language files to `lang/` directory. The package includes translation files for 40+ languages (auth, pagination, passwords, validation).

⚙️ Configuration
----------------

[](#️-configuration)

The configuration file is located at `config/locale-detector.php`:

```
return [
    /*
    |--------------------------------------------------------------------------
    | Auto Detect Locale
    |--------------------------------------------------------------------------
    |
    | Enable automatic locale detection from Accept-Language header.
    |
    */

    'auto_detect_locale' => env('AUTO_DETECT_LOCALE', true),

    /*
    |--------------------------------------------------------------------------
    | Auto Detect Preferred Language
    |--------------------------------------------------------------------------
    |
    | Use Laravel's getPreferredLanguage() method for locale detection.
    | If false, uses the Accept-Language header directly.
    |
    */

    'auto_detect_preferred_language' => env('AUTO_DETECT_PREFERRED_LANGUAGE', true),

    /*
    |--------------------------------------------------------------------------
    | Supported Locales
    |--------------------------------------------------------------------------
    |
    | List of supported locales for automatic detection.
    |
    */

    'supported_locales' => env('SUPPORTED_LOCALES', 'en,ar')
        ? explode(',', env('SUPPORTED_LOCALES', 'en,ar'))
        : ['en', 'ar'],
];
```

### Environment Variables

[](#environment-variables)

You can configure the package using environment variables in your `.env` file:

```
AUTO_DETECT_LOCALE=true
AUTO_DETECT_PREFERRED_LANGUAGE=true
SUPPORTED_LOCALES=en,ar,fr,es
```

🎯 Usage
-------

[](#-usage)

### Automatic Locale Detection

[](#automatic-locale-detection)

The middleware automatically detects the user's preferred language from the `Accept-Language` header and sets the application locale accordingly.

**No additional code required!** The middleware is automatically registered and works out of the box.

### Manual Locale Setting

[](#manual-locale-setting)

You can still manually set the locale in your code:

```
app()->setLocale('ar');
```

### Accessing Current Locale

[](#accessing-current-locale)

```
$locale = app()->getLocale();
```

🔍 Translation Key Extraction
----------------------------

[](#-translation-key-extraction)

The package provides a powerful command to extract all translation keys from your codebase.

### Basic Usage

[](#basic-usage)

```
# Extract all translation keys from the entire codebase
php artisan locale:extract-keys

# Extract keys from a specific path
php artisan locale:extract-keys --path=app

# Extract keys and save to a file
php artisan locale:extract-keys --output=translation-keys.json

# Extract keys in PHP format
php artisan locale:extract-keys --format=php --output=keys.php

# Extract keys in array format
php artisan locale:extract-keys --format=array

# Extract keys with file path and line number
php artisan locale:extract-keys --with-location

# Extract keys with location and save to JSON file
php artisan locale:extract-keys --with-location --output=translation-keys.json
```

### Options

[](#options)

OptionDescriptionDefault`--path`The path to search for translation keys`base_path()``--output`The output file path for extracted keysDisplay in console`--format`Output format (json, php, array)`json``--exclude`Comma-separated paths to excludeNone`--namespace`Filter keys by namespaceNone`--with-location`Include file path and line number for each key`false`### Examples

[](#examples)

#### Extract Keys from App Directory

[](#extract-keys-from-app-directory)

```
php artisan locale:extract-keys --path=app
```

#### Extract Keys and Save to File

[](#extract-keys-and-save-to-file)

```
php artisan locale:extract-keys --output=storage/app/translation-keys.json
```

#### Extract Keys in PHP Format

[](#extract-keys-in-php-format)

```
php artisan locale:extract-keys --format=php --output=config/translation-keys.php
```

#### Exclude Vendor and Storage Directories

[](#exclude-vendor-and-storage-directories)

```
php artisan locale:extract-keys --exclude=vendor,storage
```

#### Filter Keys by Namespace

[](#filter-keys-by-namespace)

```
php artisan locale:extract-keys --namespace=blog
```

This will only extract keys that start with `blog::`.

#### Extract Keys with Location Information

[](#extract-keys-with-location-information)

```
php artisan locale:extract-keys --with-location --output=translation-keys.json
```

This will extract keys with file path and line number information. The output will include:

- `key`: The translation key
- `file`: The relative file path
- `line`: The line number where the key was found
- `location`: A formatted string like `file:line`
- `locations`: An array of all locations where the key appears (if the same key appears multiple times)

Example output:

```
[
    {
        "key": "welcome",
        "file": "app/Http/Controllers/TestController.php",
        "line": 11,
        "location": "app/Http/Controllers/TestController.php:11",
        "locations": [
            "app/Http/Controllers/TestController.php:11",
            "app/Http/Controllers/TestController.php:12"
        ]
    }
]
```

### Supported Translation Patterns

[](#supported-translation-patterns)

The command extracts keys from the following patterns:

- `__('key')` - Laravel's translation helper
- `trans('key')` - Translation function
- `@lang('key')` - Blade directive
- `Lang::get('key')` - Lang facade method
- `Lang::trans('key')` - Lang facade trans method
- `trans_choice('key', ...)` - Translation choice function
- `__('namespace::key')` - Namespaced translations
- `trans('namespace::key')` - Namespaced translations

### Output Formats

[](#output-formats)

#### JSON Format

[](#json-format)

```
[
    "validation.required",
    "validation.email",
    "messages.welcome",
    "blog::post.title"
]
```

#### PHP Format

[](#php-format)

```
