PHPackages                             dilbrinazad/laravel-multi-lang - 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. dilbrinazad/laravel-multi-lang

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

dilbrinazad/laravel-multi-lang
==============================

A Laravel package for multilingual support

1.0.0(1y ago)010MITPHPPHP ^8.2

Since Mar 5Pushed 1y ago1 watchersCompare

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

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

Laravel MultiLang Package
=========================

[](#laravel-multilang-package)

**Laravel MultiLang** is a powerful and flexible package designed to seamlessly integrate multi-language support into your Laravel application. This package enables efficient handling of multiple languages, content translation, and language switching in a structured and scalable manner.

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

[](#table-of-contents)

1. [Installation](#installation)
2. [Configuration](#configuration)
3. [Usage](#usage)
    - [Database Migrations](#database-migrations)
    - [Seeding Languages](#seeding-languages)
    - [Model Structure](#model-structure)
    - [Traits](#traits)
    - [View Components](#view-components)
4. [Contributing](#contributing)
5. [License](#license)

---

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

[](#installation)

### Step 1: Install via Composer

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

Run the following command to install the package:

```
composer require dilbrinazad/laravel-multi-lang
```

This will add the package to your Laravel project and make it available for use.

---

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

[](#configuration)

After installation, publish the package resources using:

```
php artisan vendor:publish --provider="DilbrinAzad\LaravelMultiLang\Providers\LaravelMultiLangServiceProvider" --tag="multilang-resources"
```

This will publish the following resources:

- **Configuration File:** `config/multilang.php`
- **Database Migrations** for language management
- **Seeders** for preloading language data
- **Models** for multilingual entities
- **Controllers** for language handling
- **Traits** for reusable multilingual functionality
- **View Components** for easy language selection and input

---

Usage
-----

[](#usage)

### Database Migrations

[](#database-migrations)

Run the migration command to create the necessary tables:

```
php artisan migrate
```

This will generate three tables:

#### `languages` Table

[](#languages-table)

```
Schema::create('languages', function (Blueprint $table) {
    $table->id();
    $table->string('title'); // Display name of the language
    $table->string('name'); // Language name in English
    $table->string('country_code'); // ISO country code
    $table->string('dir'); // Text direction ('ltr' or 'rtl')
    $table->string('locale')->unique(); // Unique language identifier
    $table->boolean('status')->default(1); // Active or inactive status
    $table->timestamps();
});
```

#### `language_texts` Table

[](#language_texts-table)

```
Schema::create('language_texts', function (Blueprint $table) {
    $table->id();
    $table->text('default_content'); // Original text before translation
    $table->timestamps();
});
```

#### `language_translations` Table

[](#language_translations-table)

```
Schema::create('language_translations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('language_text_id')->constrained('language_texts')->onDelete('cascade');
    $table->foreignId('language_id')->constrained('languages')->onDelete('cascade');
    $table->text('content'); // Translated content
    $table->timestamps();
});
```

### Seeding Languages

[](#seeding-languages)

You can seed default languages by running:

```
php artisan db:seed --class=LanguageSeeder
```

By default, the following languages are included:

```
$languages = [
    ['title' => 'English', 'name' => 'English', 'country_code' => 'US', 'dir' => 'ltr', 'locale' => 'en', 'status' => 1],
    ['title' => 'Kurdish', 'name' => 'Kurdish', 'country_code' => 'KU', 'dir' => 'rtl', 'locale' => 'ku', 'status' => 1],
];
```

You can modify this list to include any language you need.

---

Model Structure
---------------

[](#model-structure)

### Language Model

[](#language-model)

```
class Language extends Model {
    protected $table = 'languages';
    protected $fillable = ['title', 'name', 'country_code', 'dir', 'locale', 'status'];
}
```

### LanguageText Model

[](#languagetext-model)

```
class LanguageText extends Model {
    protected $table = 'language_texts';
    protected $fillable = ['default_content'];

    public function translations(): HasMany {
        return $this->hasMany(LanguageTranslation::class, 'language_text_id');
    }
}
```

### LanguageTranslation Model

[](#languagetranslation-model)

```
class LanguageTranslation extends Model {
    protected $table = 'language_translations';
    protected $fillable = ['language_text_id', 'language_id', 'content'];

    public function language(): BelongsTo {
        return $this->belongsTo(Language::class);
    }
}
```

---

Traits
------

[](#traits)

### `LanguageTranslationTrait`

[](#languagetranslationtrait)

This trait simplifies storing and updating translations:

```
trait LanguageTranslationTrait {
    public function storeLangTranslation($model): void {
        DB::beginTransaction();
        try {
            foreach ($model->getTranslatableColumns() as $column) {
                $data = $model->attributes[$column];
                $defaultContent = $data[config('multilang.default_locale')] ?? null;
                $langText = LanguageText::create(['default_content' => $defaultContent]);
                foreach ($data as $locale => $content) {
                    if ($content) {
                        LanguageTranslation::create([
                            'language_text_id' => $langText->id,
                            'language_id' => $this->getLangIdByLocale($locale),
                            'content' => $content,
                        ]);
                    }
                }
                $model->attributes[$column] = $langText->id;
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }
}
```

This trait ensures that translations are efficiently stored and updated while handling errors gracefully.

---

Components
----------

[](#components)

### `MultiLanguageInput` Component

[](#multilanguageinput-component)

This component provides a customizable multilingual input field

```
class MultiLanguageInput extends Component {
      public function __construct(
        $label = '',
        $type = 'text',
        $name = '',
        $placeholder = '',
        $value = '',
        $textId = 0,
        $currentLanguage = null,
        $otherLanguages = []
    ) {
        $this->label = $label;
        $this->type = $type;
        $this->name = $name;
        $this->placeholder = $placeholder;
        $this->value = $value;
        $this->textId = $textId;
        $this->currentLanguage = $currentLanguage;
        $this->otherLanguages = $otherLanguages;
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        $currentLanguageLocale = config('multilang.default_locale');

        $languages = Language::all()->keyBy('locale');
        $currentLanguage = $languages->firstWhere('locale', $currentLanguageLocale);
        $otherLanguages = $languages->filter(function ($language) use ($currentLanguageLocale) {
            return $language->locale !== $currentLanguageLocale;
        });
        return view('components.multi-language-input', compact('currentLanguage', 'otherLanguages'));
    }
}
```

**How It Works**
----------------

[](#how-it-works)

### **1. Component Class (`MultiLanguageInput.php`)**

[](#1-component-class-multilanguageinputphp)

- The component is located in `App\View\Components\MultiLanguageInput`.
- It extends Laravel’s `Component` class, making it reusable in Blade templates.
- The constructor accepts multiple parameters for configuration:

```
   class MultiLanguageInput extends Component {
       public function __construct(
           $label = '',
           $type = 'text',
           $name = '',
           $placeholder = '',
           $value = '',
           $textId = 0,
           $currentLanguage = null,
           $otherLanguages = []
       ) {
           $this->label = $label;
           $this->type = $type;
           $this->name = $name;
           $this->placeholder = $placeholder;
           $this->value = $value;
           $this->textId = $textId;
           $this->currentLanguage = $currentLanguage;
           $this->otherLanguages = $otherLanguages;
       }
   }
```

- `$label`: The label text for the input field.
- `$type`: Input field type (default: `text`).
- `$name`: The name attribute of the input.
- `$placeholder`: Placeholder text.
- `$value`: Pre-filled value (if any).
- `$textId`: ID for retrieving translations via AJAX.
- `$currentLanguage`: The primary language for input.
- `$otherLanguages`: Additional languages for translation.
- **Fetching Languages:**

    ```
       public function render(): View|Closure|string
          {
              $currentLanguageLocale = config('multilang.default_locale');

              $languages = Language::all()->keyBy('locale');
              $currentLanguage = $languages->firstWhere('locale', $currentLanguageLocale);
              $otherLanguages = $languages->filter(function ($language) use ($currentLanguageLocale) {
                  return $language->locale !== $currentLanguageLocale;
              });
              return view('components.multi-language-input', compact('currentLanguage', 'otherLanguages'));
          }
    ```

    - It retrieves all available languages from the `languages` table.
    - It identifies the **current language** from the config file (`multilang.default_locale`).
    - It filters out other available languages for translation.
    - Passes this data to the Blade component view.

---

### **2. Blade Component (`multi-language-input.blade.php`)**

[](#2-blade-component-multi-language-inputbladephp)

- **Primary Input Field**

    - Displays an input field for the **current language**.
    - Includes a **label** and placeholder.
- **Dropdown for Other Languages**

    - If multiple languages exist, a **dropdown button** appears next to the input field.
    - Clicking the dropdown button reveals additional input fields for other languages.
    - Each language gets a separate text input.
- **JavaScript (jQuery) for Interactivity**

    - Clicking the **dropdown button** toggles the additional language fields.
    - Clicking outside the dropdown **closes it automatically**.
    - If `$textId` is provided, an AJAX request fetches saved translations and fills the input fields dynamically.

**Example Usage**
-----------------

[](#example-usage)

### **For Creating a New Entry**

[](#for-creating-a-new-entry)

```

```

### **For Updating an Existing Entry**

[](#for-updating-an-existing-entry)

```

```

The component retrieves existing translations using $lookup-&gt;name\_lang\_id. An AJAX request fetches saved translations and fills the input fields automatically.

---

Example
-------

[](#example)

**Introduction**
----------------

[](#introduction)

This guide explains how to integrate the `MultiLanguageInput` component for handling multilingual fields in Laravel using the **Hotel model** as an example.

---

**1. How It Works**
-------------------

[](#1-how-it-works)

The **MultiLanguageInput** component allows users to:

- Enter **text** in different languages.
- Retrieve **existing translations** dynamically via AJAX.
- Use a **dropdown** to toggle between language inputs.
- **Store &amp; update translations** automatically with a trait.

---

**2. Setting Up the Hotel Model**
---------------------------------

[](#2-setting-up-the-hotel-model)

### **Step 1: Create the Model and Use the Trait**

[](#step-1-create-the-model-and-use-the-trait)

In your **Hotel model**, you need to:

1. **Use the `LanguageTranslationTrait`.**
2. **Define translatable fields** in the `$translatable` array.
3. **Use Eloquent model events** (`creating` &amp; `updating`) to handle translations.

```
