PHPackages                             somar/translation - 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. somar/translation

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

somar/translation
=================

Translation Package

V1.2(2y ago)215MITPHPPHP &gt;=8.0

Since Apr 29Pushed 2y agoCompare

[ Source](https://github.com/somarkn99/laravel-translation)[ Packagist](https://packagist.org/packages/somar/translation)[ RSS](/packages/somar-translation/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

Translation Package
===================

[](#translation-package)

This package allows you to manage models and his translations in database.

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

[](#installation)

1. This package can be used with Laravel 8.0 or higher. you can install the package via composer:

```
composer require somar/translation
```

2. Optional: The service provider will automatically get registered. Or you may manually add the service provider in your config/app.php file:

```
'providers' => [
    // ...
    Somar\Translation\TranslationServiceProvider::class,
];
```

3. You should publish the migrations and seeder files:

```
php artisan vendor:publish --provider="Somar\Translation\TranslationServiceProvider"
```

- if you want to publish only migrations files:

```
php artisan vendor:publish --provider="Somar\Translation\TranslationServiceProvider" --tag=migrations
```

- if you want to publish only seeders files:

```
php artisan vendor:publish --provider="Somar\Translation\TranslationServiceProvider" --tag=seeders
```

4. Run the migrations: After the migration have been published, you can create the tables for this package by running:

```
php artisan migrate
```

5. Run the seeder

```
php artisan db:seeder --class=TranslationsLanguageSeeder
```

Automatically after executing seeding, your project will support Arabic and English languages. But, if you want to add a new language, you have to add this language in the following way:

- add code for new language in TranslationsLanguageSeeder at $all\_languages variable, like this:

```
RequestLanguage::$all_languages = ['en', 'ar', 'code for new language'];
```

- then you can add new language

```
TranslationsLanguage::create([
    'code'  => 'code for new language',
    'title' => 'new language name',
]);
```

**Note:**. you can manage Languages or modify it by dealing with translations\_languages table directly.

6. list the middleware class in the $middleware property of your app/Http/Kernel.php class:

```
protected $middlewareGroups = [
        'api' => [
            \Somar\Translation\Middleware\RequestLanguage::class,
            // ...
        ],
    ];
```

Usage Instructions
------------------

[](#usage-instructions)

### Set Up Translatable Model Class

[](#set-up-translatable-model-class)

1. After determine the tables that you want to translate some column of them, modify the model for this table by inheriting TranslatableModel, like this:

```
use Somar\Translation\Database\TranslatableModel;

class Test extends TranslatableModel
{
    // ...
}
```

2. Add new protected variable called translatable, and the type of this variable must be array. You should add the columns you want to translate from this model in the translatable variable. for example:

```
class Employee extends TranslatableModel
{
    // ...
    protected $fillable = [
        'salary'
    ];

    protected $translatable = [
        'name',
        'position',
    ];
}
```

**Note:**. you should not add the columns you want to translate in migration files. just add the another columns that have no translation. for example:

```
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->float('salary');
            $table->timestamps();
        });
    }
     /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employees');
    }
}
```

As the translatable columns are automatically stored at the translations table in database.

### Inserting Translatable Models

[](#inserting-translatable-models)

When you need to insert new records, you should instantiate a new model instance and set attributes on the model. Then, call the save method on the model instance. Note that When you adding translation for a specific column, you must assign the value as:

- string value, then all translation values take the same value.
- or as array key =&gt; value. for example:

```
class EmployeeController extends Controller
{
    // ...
    public function store(Request $request)
    {
        // Validate the request...

        $employee = new Employee();

        $employee->name = [
            'en'  => 'name in english',
            'ar'  => 'name in arabic',
        ];
        $employee->position = [
            'en'  => 'position in english',
            'ar'  => 'position in arabic',
        ];
        $employee->salary = 5000,

        $employee->save();
    }
}
```

You may use the create method to "save" a new model, like this:

```
class EmployeeController extends Controller
{
    // ...
    public function store(Request $request)
    {
        // Validate the request...

        $employee = Employee::create([
            'name'     => 'translation name',
            'position' => 'translation position',
            'salary'   => 5000,
        ]);
    }
}
```

If you want to add validate for request you can use function called translation\_rule(), this method forces the user to enter the value with its translations in all languages ​​supported in the system. for example:

```
class EmployeeController extends Controller
{
    // ...
    public function store(Request $request)
    {
        $request->validate([
            'name'      => ['required', 'array', translation_rule()],
            'position'  => ['required', 'array', translation_rule()],
            'salary'    => ['required']
        ]);

        $employee = new Employee();

        $employee->name = $request->name,
        $employee->position = $request->position,
        $employee->salary = $request->salary,

        $employee->save();
    }
}
```

### Updating Translatable Models

[](#updating-translatable-models)

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it and set any attributes you wish to update. Then, you should call the model's save method. When you update any translatable column, the old translation value delete from translations table and insert the new translation value in this table. for example:

```
class EmployeeController extends Controller
{
    // ...
    public function update($id ,Request $request)
    {
        // Validate the request...

       $employee = Employee::find($id);

       $employee->name = [
            'en'  => 'name in english',
            'ar'  => 'name in arabic',
        ];
        $employee->position = [
            'en'  => 'position in english',
            'ar'  => 'position in arabic',
        ];

        $employee->save();
    }
}
```

You may use the update method to "update" a model, like this:

```
class EmployeeController extends Controller
{
    // ...
    public function update($id ,Request $request)
    {
        // Validate the request...

       $employee = Employee::find($id);

       $employee->update = [
            'name'     => ['en'=> 'name in english','ar'=> 'name in arabic'],
            'position' => ['en'=> 'position in english','ar'=> 'position in arabic'],
       ];
    }
}
```

### Deleting Translatable Models

[](#deleting-translatable-models)

To delete a model, you may call the delete method on the model instance: When you delete a model, his translations are automatically deleted from the translation table.

```
class EmployeeController extends Controller
{
    // ...
    public function destroy($id)
    {
       $employee = Employee::find($id);

       $employee->delete();
    }
}
```

### Retrieving Translatable Models

[](#retrieving-translatable-models)

When you need to retrieve a model, you can do it by this way:

```
class EmployeeController extends Controller
{
    // ...
    public function show($id)
    {
        $employee = Employee::find($id);

        return $employee;
    }
}
```

Then the model and his translation returned in this way:

```
{
	"id": 1,
	"name": "name in english",
	"position": "position in english",
	"salary": 5000,
	"translations": {
		"name": {
			"ar": "name in arabic",
			"en": "name in english"
		},
		"position": {
			"ar": "position in english",
			"en": "position in arabic"
		}
	}
}

```

In this package you can specify which language you want to return the translatable columns in, by sending the language code you want in the headers, like this:

```
Accept-Language : en;
```

By default if you don't send the accept-language header it will take English as the default language. All This is provided by RequestLanguage middleware.

Control the Languages
---------------------

[](#control-the-languages)

### Get all available Languages

[](#get-all-available-languages)

In order to ensure compatibility between the backend and the frontend, especially when the frontend works using famous translation libraries such as i18n, you need the language code to be identical to the Language universal code, for that the entered code is controlled according to the Json file. Front End can get these languages and display them in a drop down list to ensure compatibility.

```
https://www.your-domain.com/languages/available

```

### CRUD Languages

[](#crud-languages)

1. Get All Languages: Returns the languages within your application

```
Get: https://www.your-domain.com/languages

```

2. Add new Language: send 'title' in form-data like you are insert in TranslatableModel

```
Post: https://www.your-domain.com/languages

```

3. Delete Language

```
Delete: https://www.your-domain.com/languages/:id

```

### Search within translated value

[](#search-within-translated-value)

You can do this by using the following Scope:

```
WhereTranslation

```

As in the following example:

```
$searchValue = 'your_search_value';

$products = Product::whereTranslation('name', $searchValue)->get();

```

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

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

749d ago

### Community

Maintainers

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

---

Top Contributors

[![somarkn99](https://avatars.githubusercontent.com/u/44697004?v=4)](https://github.com/somarkn99 "somarkn99 (12 commits)")[![mosab-jbara](https://avatars.githubusercontent.com/u/22756221?v=4)](https://github.com/mosab-jbara "mosab-jbara (4 commits)")[![Jawa98](https://avatars.githubusercontent.com/u/99173070?v=4)](https://github.com/Jawa98 "Jawa98 (1 commits)")

### Embed Badge

![Health badge](/badges/somar-translation/health.svg)

```
[![Health](https://phpackages.com/badges/somar-translation/health.svg)](https://phpackages.com/packages/somar-translation)
```

###  Alternatives

[barryvdh/laravel-translation-manager

Manage Laravel Translations

1.7k3.6M17](/packages/barryvdh-laravel-translation-manager)[vluzrmos/language-detector

Detect the language for your application using browser preferences, subdomains or route prefixes.

109554.8k3](/packages/vluzrmos-language-detector)[kerigard/laravel-lang-ru

Ru lang for Laravel

2116.8k](/packages/kerigard-laravel-lang-ru)[highsolutions/laravel-translation-manager

Manage Laravel Translations

1518.8k](/packages/highsolutions-laravel-translation-manager)[amendozaaguiar/laraveles-spanish-for-jetstream

Archivos de traducción al español latinoamericano para Laravel con Jetstream (auth, pagination, passwords, validation + todas las cadenas de Jetstream).

1412.1k](/packages/amendozaaguiar-laraveles-spanish-for-jetstream)

PHPackages © 2026

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