PHPackages                             mphpmaster/laravel-translatable - 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. [Database &amp; ORM](/categories/database)
4. /
5. mphpmaster/laravel-translatable

ActiveLibrary[Database &amp; ORM](/categories/database)

mphpmaster/laravel-translatable
===============================

A Laravel package for multilingual models. Set up, manage and use localized routes easily!

1.0.2(5y ago)013MITPHPPHP &gt;=7.2CI failing

Since Mar 26Pushed 5y ago1 watchersCompare

[ Source](https://github.com/mPhpMaster/laravel-translatable)[ Packagist](https://packagist.org/packages/mphpmaster/laravel-translatable)[ Docs](https://laravel-translatable.hlack.net)[ RSS](/packages/mphpmaster-laravel-translatable/feed)WikiDiscussions master Synced today

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

Introduction
============

[](#introduction)

**If you want to store translations of your models into the database, this package is for you.**

This is a Laravel package for translatable models. Its goal is to remove the complexity in retrieving and storing multilingual model instances. With this package you write less code, as the translations are being fetched/saved when you fetch/save your instance.

The full documentation can be found at [GitHub](https://github.com/mPhpMaster/laravel-translatable).

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

[](#installation)

```
composer require mphpmaster/laravel-translatable
```

Quick Example
-------------

[](#quick-example)

### **Getting translated attributes**

[](#getting-translated-attributes)

```
$book = Book::first();
echo $book->translate('en')->title; // English

App::setLocale('en');
echo $book->title; // English

App::setLocale('fr');
echo $book->title; // French
```

### **Saving translated attributes**

[](#saving-translated-attributes)

```
$book = Book::first();
echo $book->translate('en')->title; // English

$book->translate('en')->title = 'English Lang';
$book->save();

$book = Book::first();
echo $book->translate('en')->title; // English Lang
```

### **Filling multiple translations**

[](#filling-multiple-translations)

```
$data = [
  'author' => 'name',
  'en' => ['title' => 'English'],
  'fr' => ['title' => 'French'],
];
$book = Book::create($data);

echo $book->translate('fr')->title; // French
```

Routes
======

[](#routes)

?? Configure
------------

[](#-configure)

#### ?? Publish Configuration File

[](#-publish-configuration-file)

```
php artisan vendor:publish --provider="mPhpMaster\Translatable\LocalizedRoutesServiceProvider" --tag="config"
```

You will now find a `laravel-translatable.php` file in the `config` folder.

#### ?? Supported Locales

[](#-supported-locales)

##### Using Slugs

[](#using-slugs)

Add any locales you wish to support to your published `config/laravel-translatable.php` file:

```
'supported-locales' => ['en', 'nl', 'fr'],
```

This will automatically prepend a slug to your localized routes. [More on this below](#-register-routes).

##### Using Domains

[](#using-domains)

Alternatively, you can use a different domain or subdomain for each locale by configuring the `supported-locales` like this:

```
'supported-locales' => [
  'en' => 'example.com',
  'nl' => 'nl.example.com',
  'fr' => 'fr.example.com',
],
```

#### ?? Omit Slug for Main Locale

[](#-omit-slug-for-main-locale)

Specify your main locale if you want to omit its slug from the URL:

```
'omit_url_prefix_for_locale' => null
```

Setting this option to `'en'` will result, for example, in URL's like this:

- English: `/some-url` instead of the default `/en/some-url`
- Dutch: `/nl/some-url` as usual
- French: `/fr/some-url` as usual

> This option has no effect if you use domains instead of slugs.

#### ?? Use Middleware to Update App Locale

[](#-use-middleware-to-update-app-locale)

By default, the app locale will always be what you configured in `config/app.php`. To automatically update the app locale when a localized route is accessed, you need to use a middleware.

**?? Important note for Laravel 6+**

To make route model binding work in Laravel 6+ you always also need to add the middleware to the `$middlewarePriority` array in `app/Http/Kernel.php` so it runs before `SubstituteBindings`:

```
protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class, //  true
```

> This will not add the middleware to non-localized routes!

**OR, for every route using the `web` middleware group**

You can manually add the middleware to the `$middlewareGroups` array in `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'web' => [
        \Illuminate\Session\Middleware\StartSession::class, // name('about')
        ->middleware(\mPhpMaster\Translatable\Middleware\SetLocale::class);

    Route::group([
        'as' => 'admin.',
        'middleware' => [\mPhpMaster\Translatable\Middleware\SetLocale::class],
    ], function () {

        Route::get('admin/reports', ReportsController::class.'@index')
            ->name('reports.index');

    });

});
```

#### ?? Use Localizer to Detect and Set the Locale

[](#-use-localizer-to-detect-and-set-the-locale)

This package can use [codezero/laravel-localizer](https://github.com/codezero-be/laravel-localizer) to automatically detect and set the locale.

With this option disabled, the app locale will only be updated when accessing localized routes.

With this option enabled, the app locale can also be updated when accessing non-localized routes. For non-localized routes it will look for a preferred locale in the session, in a cookie or in the browser. Additionally, it will also store the app locale in the session and in a cookie.

> Enabling this option can be handy if you have, for example, a generic homepage and you want to know the preferred locale.

To enable this option, set it to `true` in the published config file.

```
'use_localizer' => true
```

This option only has effect on routes that use our `SetLocale` middleware.

> You can review [codezero/laravel-localizer](https://github.com/codezero-be/laravel-localizer), publish its config file and tweak it as needed. The only option we will override is `supported-locales`, to match the option in our own config file.

#### ?? Set Options for the Current Localized Route Group

[](#-set-options-for-the-current-localized-route-group)

To set an option for one localized route group only, you can specify it as the second parameter of the localized route macro. This will override the config file settings.

```
Route::localized(function () {

    Route::get('about', AboutController::class.'@index')
        ->name('about');

}, [
    'supported-locales' => ['en', 'nl', 'fr'],
    'omit_url_prefix_for_locale' => null,
    'use_locale_middleware' => false,
]);
```

? Register Routes
-----------------

[](#-register-routes)

Example:

```
// Not localized
Route::get('home', HomeController::class.'@index')
    ->name('home');

// Localized
Route::localized(function () {

    Route::get('about', AboutController::class.'@index')
        ->name('about');

    Route::name('admin.')->group(function () {
        Route::get('admin/reports', ReportsController::class.'@index')
            ->name('reports.index');
    });

});
```

In the above example there are 5 routes being registered. The routes defined in the `Route::localized` closure are automatically registered for each configured locale. This will prepend the locale to the route's URI and name. If you configured custom domains, it will use those instead of the slugs.

URIName/homehome/en/abouten.about/nl/aboutnl.about/en/admin/reportsen.admin.reports.index/nl/admin/reportsnl.admin.reports.indexIf you set `omit_url_prefix_for_locale` to `'en'` in the configuration file, the resulting routes look like this:

URIName/homehome/abouten.about/nl/aboutnl.about/admin/reportsen.admin.reports.index/nl/admin/reportsnl.admin.reports.index**?? Beware that you don't register the same URL twice when omitting the locale.**You can't have a localized `/about` route and also register a non-localized `/about` route in this case. The same idea applies to the `/` (root) route! Also note that the route names still have the locale prefix.

### ? Localized `404` Pages

[](#-localized-404-pages)

By default, Laravel's `404` pages don't go trough the middleware and have no `Route::current()` associated with it. Not even when you create your custom `errors.404` view. Therefor, the locale can't be set to match the requested URL automatically via middleware.

To enable localized `404` pages, you need to register a `fallback` route and make sure it has the `SetLocale` middleware. This is basically a catch all route that will trigger for all non existing URL's.

```
Route::fallback(function () {
    return response()->view('errors.404', [], 404);
})->middleware(\mPhpMaster\Translatable\Middleware\SetLocale::class);
```

Another thing to keep in mind is that a `fallback` route returns a `200` status by default. So to make it a real `404` you need to return a `404` response yourself.

Fallback routes will not be triggered when:

- your existing routes throw a `404` error (as in `abort(404)`)
- your existing routes throw a `ModelNotFoundException` (like with route model binding)
- your existing routes throw any other exception

Because those routes are in fact registered, the `404` page will have the correct `App::getLocale()` set.

[Here is a good read about fallback routes](https://themsaid.com/laravel-55-better-404-response-20170921).

### ? Generate Route URL's

[](#-generate-route-urls)

You can get the URL of your named routes as usual, using the `route()` helper.

##### ? The ugly way...

[](#-the-ugly-way)

Normally you would have to include the locale whenever you want to generate a URL:

```
$url = route(app()->getLocale().'.admin.reports.index');
```

##### ? A much nicer way...

[](#-a-much-nicer-way)

Because the former is rather ugly, this package overwrites the `route()` function and the underlying `UrlGenerator` class with an additional, optional `$locale` argument and takes care of the locale prefix for you. If you don't specify a locale, either a normal, non-localized route or a route in the current locale is returned.

```
$url = route('admin.reports.index'); // current locale
$url = route('admin.reports.index', [], true, 'nl'); // dutch URL
```

This is the new route helper signature:

```
route($name, $parameters = [], $absolute = true, $locale = null)
```

A few examples (given the example routes we registered above):

```
app()->setLocale('en');
app()->getLocale(); // 'en'

$url = route('home'); // /home (normal routes have priority)
$url = route('about'); // /en/about (current locale)

// Get specific locales...
// This is most useful if you want to generate a URL to switch language.
$url = route('about', [], true, 'en'); // /en/about
$url = route('about', [], true, 'nl'); // /nl/about

// You could also do this, but it kinda defeats the purpose...
$url = route('en.about'); // /en/about
$url = route('en.about', [], true, 'nl'); // /nl/about
```

> **Note:** in a most practical scenario you would register a route either localized **or** non-localized, but not both. If you do, you will always need to specify a locale to get the URL, because non-localized routes always have priority when using the `route()` function.

### ? Redirect to Routes

[](#-redirect-to-routes)

Laravel's `Redirector` uses the same `UrlGenerator` as the `route()` function behind the scenes. Because we are overriding this class, you can easily redirect to your routes.

```
return redirect()->route('home'); // non-localized route, redirects to /home
return redirect()->route('about'); // localized route, redirects to /en/about (current locale)
```

You can't redirect to URL's in a specific locale this way, but if you need to, you can of course just use the `route()` function.

```
return redirect(route('about', [], true, 'nl')); // localized route, redirects to /nl/about
```

### ?? Generate Localized Versions of the Current URL

[](#-generate-localized-versions-of-the-current-url)

To generate a URL for the current route in any locale, you can use this `Route` macro:

##### With Route Model Binding

[](#with-route-model-binding)

If your route uses a localized key (like a slug) and you are using [route model binding](#-route-model-binding), then the key will automatically be localized.

```
$current = \Route::localizedUrl(); // /en/books/en-slug
$en = \Route::localizedUrl('en'); // /en/books/en-slug
$nl = \Route::localizedUrl('nl'); // /nl/books/nl-slug
```

If you have a route **with multiple keys**, like `/en/books/{id}/{slug}`, then you can pass the parameters yourself (like in the example without route model binding below) or you can implement this interface in your model:

```
use mPhpMaster\Translatable\ProvidesRouteParameters;
use Illuminate\Database\Eloquent\Model;

class Book extends Model implements ProvidesRouteParameters
{
    public function getRouteParameters($locale = null)
    {
        return [
            $this->id,
            $this->getSlug($locale) // Add this method yourself of course :)
        ];
    }
}
```

Now, as long as you use route model binding, you can still just do:

```
$current = \Route::localizedUrl(); // /en/books/en-slug
$en = \Route::localizedUrl('en'); // /en/books/en-slug
$nl = \Route::localizedUrl('nl'); // /nl/books/nl-slug
```

##### Without Route Model Binding

[](#without-route-model-binding)

If you don't use [route model binding](#-route-model-binding) and you need a localized slug in the URL, then you will have to pass it manually.

For example:

```
$nl = \Route::localizedUrl('nl'); // Wrong: /nl/books/en-slug
$nl = \Route::localizedUrl('nl', [$book->getSlug('nl')]); // Right: /nl/books/nl-slug
```

The `getSlug()` method is just for illustration, so you will need to implement that yourself of course.

### ?? Generate Signed Route URL's

[](#-generate-signed-route-urls)

Generating a [signed route URL](https://laravel.com/docs/urls#signed-urls) is just as easy.

Pass it the route name, the necessary parameters and you will get the URL for the current locale.

```
$signedUrl = URL::signedRoute('reset.password', ['user' => $id], now()->addMinutes(30));
```

You can also generate a signed URL for a specific locale:

```
$signedUrl = URL::signedRoute($name, $parameters, $expiration, true, 'nl');
```

Check out the [Laravel docs](https://laravel.com/docs/urls#signed-urls) for more info on signed routes.

### ? Translate Routes

[](#-translate-routes)

If you want to translate the segments of your URI's, create a `routes.php` language file for each locale you [configured](#configure-supported-locales):

```
resources
 ??? lang
      ??? en
      ?    ??? routes.php
      ??? nl
           ??? routes.php

```

In these files, add a translation for each segment.

```
// lang/nl/routes.php
return [
    'about' => 'over',
    'us' => 'ons',
];
```

Now you can use our `Lang::uri()` macro during route registration:

```
Route::localized(function () {

    Route::get(Lang::uri('about/us'), AboutController::class.'@index')
        ->name('about.us');

});
```

Note that in order to find a translated version of a route, you will need to give your routes a name. If you don't name your routes, only the parameters (model route keys) will be translated, not the "hard-coded" slugs.

The above will generate:

- /en/about/us
- /nl/over/ons

> If a translation is not found, the original segment is used.

? Route Parameters
------------------

[](#-route-parameters)

Parameter placeholders are not translated via language files. These are values you would provide via the `route()` function. The `Lang::uri()` macro will skip any parameter placeholder segment.

If you have a model that uses a route key that is translated in the current locale, then you can still simply pass the model to the `route()` function to get translated URL's.

An example...

**Given we have a model like this:**

```
class Book extends \Illuminate\Database\Eloquent\Model
{
    public function getRouteKey()
    {
        $slugs = [
            'en' => 'en-slug',
            'nl' => 'nl-slug',
        ];

        return $slugs[app()->getLocale()];
    }
}
```

> **TIP:** checkout [spatie/laravel-translatable](https://github.com/spatie/laravel-translatable) for translatable models.

**If we have a localized route like this:**

```
Route::localized(function () {

    Route::get('books/{book}', BooksController::class.'@show')
        ->name('books.show');

});
```

**We can now get the URL with the appropriate slug:**

```
app()->setLocale('en');
app()->getLocale(); // 'en'

$book = new Book;

$url = route('books.show', [$book]); // /en/books/en-slug
$url = route('books.show', [$book], true, 'nl'); // /nl/books/nl-slug
```

?� Route Model Binding
----------------------

[](#-route-model-binding)

If you enable the [middleware](#-use-middleware-to-update-app-locale) included in this package, you can use [Laravel's route model binding](https://laravel.com/docs/routing#route-model-binding)to automatically inject models with localized route keys in your controllers.

All you need to do is add a `resolveRouteBinding()` method to your model. Check [Laravel's documentation](https://laravel.com/docs/routing#route-model-binding)for alternative ways to enable route model binding.

```
public function resolveRouteBinding($value)
{
    // Perform the logic to find the given slug in the database...
    return $this->where('slug->'.app()->getLocale(), $value)->firstOrFail();
}
```

> **TIP:** checkout [spatie/laravel-translatable](https://github.com/spatie/laravel-translatable) for translatable models.

? Cache Routes
--------------

[](#-cache-routes)

In production you can safely cache your routes per usual.

```
php artisan route:cache
```

? Testing
---------

[](#-testing)

```
composer test
```

Credits
-------

[](#credits)

- [hlaCk](https://github.com/mPhpMaster) *author*

Versions
--------

[](#versions)

PackageLaravelPHP**v1.0 - v1.0**`5.8.* / 6.* / 7.* / 8.*``>=7.2`

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

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

3

Last Release

1870d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/653f207f1b16ec4055eea8fd8699991febd6a1a0201011ab3d1a6ece3bbfd511?d=identicon)[mPhpMaster](/maintainers/mPhpMaster)

---

Top Contributors

[![mPhpMaster](https://avatars.githubusercontent.com/u/59211285?v=4)](https://github.com/mPhpMaster "mPhpMaster (6 commits)")

---

Tags

laravellanguagedatabasetranslationmultilanguage

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mphpmaster-laravel-translatable/health.svg)

```
[![Health](https://phpackages.com/badges/mphpmaster-laravel-translatable/health.svg)](https://phpackages.com/packages/mphpmaster-laravel-translatable)
```

###  Alternatives

[astrotomic/laravel-translatable

A Laravel package for multilingual models

1.4k7.7M112](/packages/astrotomic-laravel-translatable)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[dragon-code/migrate-db

Easy data transfer from one database to another

15717.4k](/packages/dragon-code-migrate-db)[ntanduy/cloudflare-d1-database

Easy configuration and setup for D1 Database connections in Laravel.

215.4k](/packages/ntanduy-cloudflare-d1-database)

PHPackages © 2026

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