itstructure / laravel-multilingual-tools
Laravel package for multilingual content manage
Package info
github.com/itstructure/laravel-multilingual-tools
pkg:composer/itstructure/laravel-multilingual-tools
Requires
- php: >=7.3.0
- laravel/framework: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
Requires (Dev)
- orchestra/testbench: ^6.0|^7.0|^8.0|^9.0|^10.0|^11.0
- phpunit/phpunit: ^9.0|^10.0|^11.0|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Laravel multilingual tools
1 Introduction
MULT - Package for the Laravel framework to content manage with different languages.
For example, you can store pages in English, Russian, French, German and some another languages...
It is you who add new languages to your application.
All multilingual fields will be with a language postfix, as in example:
title_en, description_en, content_en
title_ru, description_ru, content_ru, e t. c.
2 Dependencies
- laravel 8+ | 9+ | 10+ | 11+ | 12+ | 13+
- php >= 7.3
- composer
3 Installation
Note!
Version 2.x is for laravel 8, 9, 10, 11, 12, 13.
Version 1.x is for laravel 7. You can use branch laravel7-mult with 1.x versions.
3.1 General installation from remote repository
Run the composer command:
composer require itstructure/laravel-multilingual-tools "^2.1.0"
3.2 If you are testing this package from local server directory
In application composer.json file set the repository, as in example:
"repositories": [ { "type": "path", "url": "../laravel-multilingual-tools" } ],
Here,
../laravel-multilingual-tools - directory name, which has the same directory level as your project application and contains MULT package.
Then run command:
composer require itstructure/laravel-multilingual-tools:dev-master --prefer-source
3.3 Next internal installation steps
-
Publish files.
-
To publish migrations run command:
php artisan mult:publish --only=migrationsIt stores migration file to
database/migrationsfolder. There is a migration to create languages table. -
To publish seeder run command:
php artisan mult:publish --only=seedersIt stores seeder files to
database/seedersfolder. There is a seeder to create a first English language DB entry as a default. -
To publish all parts run command without
onlyargument:php artisan mult:publish
Else you can use
--forceargument to rewrite already published files. -
-
Run command to run migration and seed:
php artisan mult:databaseThe next will be acted:
-
A table languages will be created.
-
A first English language will be stored as a default.
Or optional:
To run just migration
php artisan mult:database --only=migrateTo run just seed
php artisan mult:database --only=seed-
Alternative variant for seeders.
You can set published
MultSeederseeder class in to a specialDatabaseSeeder:use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder { public function run() { $this->call(MultSeeder::class); } }
and run command:
php artisan db:seed.
-
4 Usage
Notes:
-
There are no controllers, views, routes and another CRUD elements to manage languages. There is just a model
Language. This CRUD you must to create by yourself in your application. -
There are no controllers, models, views, routes and another CRUD elements to manage entity content. There are just base classes, which are written below. CRUDs you must to create by yourself in your application.
4.1 Migration part
First, before a develop multilingual application, make migrations with extending from MultilingualMigration base class.
Example for pages table:
use Illuminate\Database\Schema\Blueprint; use Itstructure\Mult\Classes\MultilingualMigration;
class CreatePagesTable extends MultilingualMigration { public function up() { $this->createMultilingualTable('pages', function (Blueprint $table) { $table->string('title', 64); $table->text('description')->nullable(); }, function (Blueprint $table) { $table->unsignedTinyInteger('active')->default(0)->index(); $table->string('alias', 64)->index(); }); } public function down() { $this->dropMultilingualTable('pages'); } }
Here,
createMultilingualTable() method provides:
-
First argument: table name.
-
Second argument: a callable with multilingual fields.
-
Third argument: a callable with simple fields.
After applying a migration, two tables will be created automatically:
-
pages - to store a simple data.
-
pages_languages - to store translates, some entries for concrete pages entry.
Note: Timestamps created automatically for both tables.
And the next special columns for pages_languages table with foreign keys will be created automatically:
-
column pages_id. Foreign key to pages table
pages_languages(pages_id) -> pages(id) -
column languages_id. Foreign key to languages table
pages_languages(languages_id) -> languages(id)
Example with already stored data:
Main table "pages"
| id | active | alias | created_at | updated_at |
|----|--------|-------------|---------------------|---------------------|
| 1 | 1 | first-page | 2020-01-14 18:06:33 | 2020-01-14 18:06:33 |
| 2 | 1 | second-page | 2020-01-14 18:10:00 | 2020-01-14 18:10:00 |
| 3 | 0 | third-page | 2020-01-14 19:05:15 | 2020-01-14 19:05:15 |
Translate table "pages_languages"
| pages_id | languages_id | title | description | created_at | updated_at |
|----------|--------------|------------|----------------------|---------------------|---------------------|
| 1 | 1 | Page 1 | Description 1 | 2020-01-14 18:06:33 | 2020-01-14 18:06:33 |
| 1 | 2 | Страница 1 | Описание 1 | 2020-01-14 18:06:33 | 2020-01-14 18:06:33 |
| 2 | 1 | Page 2 | Description 2 | 2020-01-14 18:10:00 | 2020-01-14 18:10:00 |
| 3 | 1 | Page 3 | Description 3 | 2020-01-14 19:05:15 | 2020-01-14 19:05:15 |
| 3 | 2 | Страница 3 | Описание 3 | 2020-01-14 19:05:15 | 2020-01-14 19:05:15 |
Language table "languages"
| id | locale | short_name | name | default | created_at | updated_at |
|----|--------|------------|---------|---------|---------------------|---------------------|
| 1 | en-US | en | English | 1 | 2020-01-14 18:06:33 | 2020-01-14 18:06:33 |
| 2 | ru-RU | ru | Русский | 0 | 2020-01-14 18:10:00 | 2020-01-14 18:10:00 |
4.2 Model part
Notes:
-
Access to multilingual value from a model entry is by using a language postfix. Example:
$model = Page::findOrFail($id); echo $model->title_en;
-
Set a new multilingual value for a model is by using a language postfix. Example:
$model = Page::findOrFail($id); $model->title_en = 'New title value'; $model->save();
-
To show a list of entries with translates, load the translates together with the entries. Then
title_en,title_ru... are taken without new database queries:$pages = Page::with('translateList')->get();
4.2.1 Main simple model
Create a main model for base table and use MultilingualModelTrait.
Example model for pages table:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Itstructure\Mult\Traits\MultilingualModelTrait;
class Page extends Model { use MultilingualModelTrait; protected $table = 'pages'; protected $fillable = ['active', 'alias']; }
4.2.2 Translate model
Create a model for translates table.
Example model for pages_languages table:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Itstructure\Mult\Models\Language;
class PageLanguage extends Model { protected $table = 'pages_languages'; protected $fillable = ['pages_id', 'languages_id', 'title', 'description']; public function page() // It is not necessary to create { return $this->hasOne(Page::class, 'id', 'pages_id'); } public function language() // It is not necessary to create { return $this->hasOne(Language::class, 'id', 'languages_id'); } }
It is not necessary to create relation methods here, such as: page(), language(). It is additional.
4.3 Validation requests part
This request classes can be useful in controller's methods.
namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Itstructure\Mult\Models\Language; use Itstructure\Mult\Helpers\MultilingualHelper;
class StorePageRequest extends FormRequest { protected $shortLanguageList = []; public function __construct() { parent::__construct(); $this->shortLanguageList = Language::shortLanguageList(); } public function authorize() { return true; } public function rules() { $multilingualRules = MultilingualHelper::fieldsTransformer([ 'title' => 'required|string|min:3|max:64', 'description' => 'nullable|string' ], function ($fieldValue) { return $fieldValue; }, $this->shortLanguageList); return array_merge([ 'active' => 'required|numeric', 'alias' => 'required|string|min:3|max:64' ], $multilingualRules); } public function attributes() { $multilingualAttributes = MultilingualHelper::fieldsTransformer([ 'title' => __('messages.title'), 'description' => __('messages.description') ], function ($fieldValue) { return $fieldValue; }, $this->shortLanguageList); return array_merge([ 'active' => __('messages.activity'), 'alias' => __('messages.alias') ], $multilingualAttributes); } }
Here rules() method makes the next result:
[
"active" => "required|numeric",
"alias" => "required|string|min:3|max:64",
"title_en" => "required|string|min:3|max:64",
"title_ru" => "required|string|min:3|max:64",
"description_en" => "nullable|string",
"description_ru" => "nullable|string"
]
4.4 Controller part
Short page controller example just to create entry:
namespace App\Http\Controllers; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Routing\Controller; use Itstructure\Mult\Models\Language; use Itstructure\Mult\Helpers\MultilingualHelper; use App\Models\Page; use App\Http\Requests\StorePageRequest;
class PageController extends Controller { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function create() { $languageList = Language::languageList(); return view('page.create', compact('languageList')); } public function store(StorePageRequest $request) { MultilingualHelper::fill(new Page(), $request->all())->save(); return redirect()->route('page_list'); } }
4.5 View template part
Short example for page.create blade view template:
<form action="{{ route('page_store') }}" method="post"> <ul class="nav nav-tabs"> @foreach($languageList as $langModel) <li class="nav-item"> <a class="nav-link @if($langModel->default == 1)active @endif" data-toggle="tab" href="#lang_{{ $langModel->short_name }}"> {{ $langModel->name }} </a> </li> @endforeach </ul> <div class="tab-content my-2"> @foreach($languageList as $langModel) <div class="tab-pane fade @if($langModel->default == 1)show active @endif" id="lang_{{ $langModel->short_name }}"> <div class="row"> <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-4"> <div class="form-group"> <label for="page_title_{{ $langModel->short_name }}">{!! __('messages.title') !!}</label> <input id="page_title_{{ $langModel->short_name }}" type="text" class="form-control @if ($errors->has('title_'.$langModel->short_name)) is-invalid @endif" name="title_{{ $langModel->short_name }}" value="{{ old('title_'.$langModel->short_name, !empty($model) ? $model->{'title_'.$langModel->short_name} : null) }}"> @if ($errors->has('title_'.$langModel->short_name)) <div class="invalid-feedback"> <strong>{{ $errors->first('title_'.$langModel->short_name) }}</strong> </div> @endif </div> </div> </div> <div class="row"> <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-4"> <div class="form-group"> <label for="page_description_{{ $langModel->short_name }}">{!! __('messages.description') !!}</label> <input id="page_description_{{ $langModel->short_name }}" type="text" class="form-control @if ($errors->has('description_'.$langModel->short_name)) is-invalid @endif" name="description_{{ $langModel->short_name }}" value="{{ old('description_'.$langModel->short_name, !empty($model) ? $model->{'description_'.$langModel->short_name} : null) }}"> @if ($errors->has('description_'.$langModel->short_name)) <div class="invalid-feedback"> <strong>{{ $errors->first('description_'.$langModel->short_name) }}</strong> </div> @endif </div> </div> </div> </div> @endforeach </div> <div class="row mb-3"> <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-4"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="page_active_input" name="active" value="1" class="custom-control-input" @if(old('active', !empty($model) ? $model->active : 1) == 1) checked @endif > <label class="custom-control-label" for="page_active_input">{!! __('messages.active') !!}</label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" id="page_inactive_input" name="active" value="0" class="custom-control-input" @if(old('active', !empty($model) ? $model->active : 1) == 0) checked @endif > <label class="custom-control-label" for="page_inactive_input">{!! __('messages.inactive') !!}</label> </div> </div> </div> <button class="btn btn-primary" type="submit">Create</button> <input type="hidden" value="{!! csrf_token() !!}" name="_token"> </form>
Tests
The package has its own tests. They check the multilingual migration, saving and reading of translates, the default language, the helper, the seeder and the mult:database command.
Good to know before you start:
- The tests do not need a database server and do not need a
.envfile. They use SQLite in memory, everything is created and deleted automatically. - To run the tests on MySQL / MariaDB instead, set environment variables
DB_CONNECTION=mysql,DB_HOST,DB_PORT,DB_DATABASE,DB_USERNAME,DB_PASSWORD. Use an empty test database: all its tables are deleted before each test. - The tests work on all supported versions: PHP 7.3 ... 8.5 and Laravel 8 ... 13.
- When you install dependencies of the package, the
vendorfolder and thecomposer.lockfile appear in the package folder. It is normal. They are in.gitignore, so they will not get into git.
Below there are several ways to run the tests. Choose the one, which fits you.
Way 1. You have PHP and Composer on your computer
-
Get the package source code.
If you have git, run command:
git clone https://github.com/itstructure/laravel-multilingual-tools.gitIf you do not have git, open https://github.com/itstructure/laravel-multilingual-tools, press the green Code button, then Download ZIP, and unpack the archive.
-
Go to the package folder:
cd laravel-multilingual-tools -
Install dependencies (it is enough to do it once):
composer installComposer itself chooses the Laravel and PHPUnit versions, which fit your PHP version.
Note! PHP must have
pdo_sqliteandmbstringextensions. Usually they are already enabled. If not, Composer or the tests will tell you about it. -
Run the tests:
composer testOr the same directly:
- Linux / macOS:
vendor/bin/phpunit - Windows:
vendor\bin\phpunit
- Linux / macOS:
-
If you want to run only one test, add
--filterwith the test name:vendor/bin/phpunit --filter testDefaultTranslate
If everything is fine, you will see a message like: OK (21 tests, 59 assertions).
Way 2. You have nothing except Docker
You do not need to install PHP and Composer. Docker downloads them by itself.
-
Get the package source code and go to the package folder, as in steps 1 and 2 of Way 1.
-
Install dependencies (it is enough to do it once).
For Linux, macOS and WSL terminal:
docker run --rm --user "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD":/app -w /app composer:2 composer update --no-interaction
For Windows PowerShell:
docker run --rm -v "${PWD}:/app" -w /app composer:2 composer update --no-interaction
Here:
--user "$(id -u):$(id -g)"- files in thevendorfolder will belong to you, not to therootuser. In Windows PowerShell it is not needed.-v "$PWD":/app- the current folder (package folder) is available inside the container as/app.
-
Run the tests.
For Linux, macOS and WSL terminal:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app php:8.4-cli php vendor/bin/phpunit
For Windows PowerShell:
docker run --rm -v "${PWD}:/app" -w /app php:8.4-cli php vendor/bin/phpunit
To run only one test, add
--filter test_nameto the end of the command.
Note! In step 2 Composer installs the newest versions of Laravel and PHPUnit. They need a new PHP, so in step 3 use php:8.4-cli or newer. To check an old PHP or Laravel version, see Way 3.
Way 3. Check a specific PHP and Laravel version with Docker
It is useful, when you want to make sure that the package works for example on PHP 7.3 with Laravel 8.
-
Choose a pair of versions from the table:
PHP image Laravel Testbench php:7.3-cli8.*6.*php:8.0-cli9.*7.*php:8.1-cli10.*8.*php:8.2-cli11.*9.*php:8.3-cli12.*10.*php:8.3-cli13.*11.*Testbench (
orchestra/testbench) is a tool for testing Laravel packages. Each Laravel version needs its own Testbench version, that is why it is in the table. -
Go to the package folder. If you have already installed dependencies before, delete the
vendorfolder and thecomposer.lockfile. -
Install dependencies for the chosen pair. Example for PHP 7.3 + Laravel 8 (Linux, macOS, WSL terminal):
docker run --rm --user "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD":/app -w /app composer:2 sh -c "composer config platform.php 7.3.33 && composer config policy.advisories.block false && composer require --no-update 'laravel/framework:8.*' && composer require --dev --no-update 'orchestra/testbench:6.*' && composer update --no-interaction --no-plugins"
What this command does:
composer config platform.php 7.3.33- tells Composer to choose packages for PHP 7.3, because Composer itself works on a newer PHP inside its container.composer config policy.advisories.block false- allows installing old Laravel versions. New Composer refuses to install versions with known security advisories. It is OK for running tests, but never do it in a real project.composer require --no-update ...- sets the chosen Laravel and Testbench versions.--no-plugins- old Laravel versions bring Composer plugins, which are not needed for tests and are blocked by new Composer.
For another pair, change
7.3.33,8.*and6.*to the values from the table. Forplatform.phpyou can write any version of the chosen PHP, for example7.3.33,8.0.30,8.2.0. -
Run the tests with the PHP image from the table:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app php:7.3-cli php vendor/bin/phpunit
-
Important! The command in step 3 changes the
composer.jsonfile of the package. When you finish, return it back and delete the installed files:git checkout composer.jsonAnd delete the
vendorfolder and thecomposer.lockfile.If you downloaded the package as ZIP (without git), just download and unpack it again.
Way 4. Automatic tests on GitHub
You do not need to do anything. After each push and each pull request, GitHub runs the tests by itself on all version pairs from the table above (and a few more).
Results are on the Actions tab of the repository: https://github.com/itstructure/laravel-multilingual-tools/actions
Green check mark - all tests passed. Red cross - something is broken, open it to see the details.
The settings are in the .github/workflows/tests.yml file.
If the package is installed in your Laravel project
-
Your project tests and the package tests do not mix.
When you run tests of your project (
composer test,php artisan testorvendor/bin/phpunitin the project folder), only tests of your project are run. The projectphpunit.xmlfile points to the projecttestsfolder, and the package lies invendor/itstructure/laravel-multilingual-tools. So the package tests are not run there. -
Usually there are no package tests in your project at all.
By default Composer downloads the package as an archive. The
testsfolder, the.githubfolder and thephpunit.xml.distfile are excluded from this archive (see the.gitattributesfile), because they are not needed for the package to work. So invendor/itstructure/laravel-multilingual-toolsthere is only the package itself. -
Exception: installation with
--prefer-source.If the package is installed with
--prefer-source(Composer makesgit cloneinstead of downloading an archive), or from a local folder (see "If you are testing this package from local server directory" above), then the whole repository is in the project, the tests too.It does not break anything: your project tests still do not run them.
-
How to run the package tests in this case.
Do not run them through your project, the project has no tools needed for the package tests.
Run them in the package folder itself, as described in Way 1 or Way 2:
- If the package is installed from a local folder (
"type": "path"), go to that local folder, for example../laravel-multilingual-tools. - Otherwise, just clone the package repository to a separate folder.
- If the package is installed from a local folder (
License
Copyright © 2020-2026 Andrey Girnik girnikandrey@gmail.com.
Licensed under the MIT license. See LICENSE.txt for details.
