PHPackages                             genl/matice - 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. genl/matice

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

genl/matice
===========

Use your Laravel translations in JavaScript. Generates a Blade directive exporting all of your Laravel translations and provides a nice trans() helper function in JavaScript.

1.2.1(1y ago)101339.4k↓13.6%15[1 issues](https://github.com/GENL/matice/issues)[2 PRs](https://github.com/GENL/matice/pulls)2MITPHP

Since Oct 16Pushed 1y ago7 watchersCompare

[ Source](https://github.com/GENL/matice)[ Packagist](https://packagist.org/packages/genl/matice)[ Docs](https://github.com/genl/matice)[ RSS](/packages/genl-matice/feed)WikiDiscussions 1.x Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (17)Used By (2)

Use your Laravel translations in JavaScript
===========================================

[](#use-your-laravel-translations-in-javascript)

[![Latest Version on Packagist](https://camo.githubusercontent.com/441d57d4f52fa15ac24182d1ac340002e6f3f91b93676560969b7ab90ffc7b55/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f67656e6c2f6d61746963652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/genl/matice)[![Latest Version on NPM](https://camo.githubusercontent.com/13a021beaf5c2a510fc1d6560bbd29b260b1233a0924ebf6a787d967335ec461/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f762f6d61746963652e7376673f7374796c653d666c6174)](https://npmjs.com/package/matice)[![Tests](https://github.com/GENL/matice/actions/workflows/tests.yml/badge.svg)](https://github.com/GENL/matice/actions/workflows/tests.yml)[![Total Downloads on packagist](https://camo.githubusercontent.com/0172155fcf4197a6a5c30541d6bacac2c89b97ea80550c3e5808e857ecbdd5df/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f67656e6c2f6d61746963652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/genl/matice/stats)[![Downloads on NPM](https://camo.githubusercontent.com/b61f92277d4aded51434ef50a1872e82a81052469f8e9f3564626e5153084fda/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f64742f6d61746963652e7376673f7374796c653d666c6174)](https://www.npmjs.com/package/matice)

[![Logo](https://camo.githubusercontent.com/049109bde5365197b56d54023a40af8ae038287f2e2acf89dae950daf51b4a1c/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f4d61746963652e706e673f7468656d653d6461726b267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d67656e6c2532466d6174696365267061747465726e3d617263686974656374267374796c653d7374796c655f31266465736372697074696f6e3d5573652b796f75722b4c61726176656c2b7472616e736c6174696f6e732b696e2b4a617661536372697074266d643d312673686f7757617465726d61726b3d3026666f6e7453697a653d313030707826696d616765733d63756265)](https://camo.githubusercontent.com/049109bde5365197b56d54023a40af8ae038287f2e2acf89dae950daf51b4a1c/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f4d61746963652e706e673f7468656d653d6461726b267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d67656e6c2532466d6174696365267061747465726e3d617263686974656374267374796c653d7374796c655f31266465736372697074696f6e3d5573652b796f75722b4c61726176656c2b7472616e736c6174696f6e732b696e2b4a617661536372697074266d643d312673686f7757617465726d61726b3d3026666f6e7453697a653d313030707826696d616765733d63756265)

Matice creates a Blade directive that you can include in your views. It will export a JavaScript object of your Laravel application's translations, keyed by their names (aliases, lang, filenames, folders name), as well as globals trans(), \_\_() and transChoice() helper functions which you can use to access your translations in your JavaScript.

- [Installation](#installation)
- [Usage](#usage)
    - [Examples](#examples)
    - [trans](#trans)
    - [Update locale](#update-locale)
    - [Pluralization](#pluralization)
    - [Trans Choice](#trans-choice)
    - [underscore function](#underscore-function)
    - [Default Values](#default-values)
    - [Retrieve the current locale](#retrieve-the-current-locale)
    - [Force locale](#force-locale)
- [Filtering translations](#filtering-translations)
    - [Filtering namespaces](#filtering-namespaces)
- [Use with SPA](#use-with-spa)
- [Using with Vue Components](#using-with-vue-components)
- [Dive Deeper](#dive-deeper)

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

[](#installation)

You can install the package via composer:

```
composer require genl/matice
```

1. ##### Include our Blade directive (`@translations`) somewhere in your template before your main application JavaScript is loaded—likely in the header somewhere.

    [](#include-our-blade-directive-translations-somewhere-in-your-template-before-your-main-application-javascript-is-loadedlikely-in-the-header-somewhere)
2. ##### Publish the vendor if you want to customize config:

    [](#publish-the-vendor-if-you-want-to-customize-config)

```
php artisan vendor:publish --provider="Genl\Matice\MaticeServiceProvider"
```

Matice is available as an NPM `matice` package which exposes the `trans()` function for use in frontend applications that do not use Blade. You can install the NPM package with:

```
// With yarn
yarn add matice

With npm
npm install matice
```

or load it from a CDN:

```

```

- Note that the JavaScript package only contains the translations logic. You have to generate your translations file and make it available to your frontend app. The blade directive `@translations` will do it for you anytime you reload the page.

**TypeScript support**

Matice is fully written in TypeScript so, it's compatible with TypeScript projects.

Usage
-----

[](#usage)

- ##### Core concepts

    [](#core-concepts)

Matice comes with almost the same localization concepts as Laravel. Read more about [Laravel localization](https://laravel.com/docs/localization)

This package uses the `@translations` directive to inject a JavaScript object containing all of your application's translations, keyed by their names. This collection is available globally on the client side in the `window.Matice` object. The `@translations` directive accepts a list of locales to be loaded under th form of an array or a comma seperated string. If no locales are given, all the translations will be loaded.

#### Examples

[](#examples)

import the `trans()` function like follow:

```
@translations(['en', 'fr'])

or

@translations('en, fr')
```

The package also creates an optional `trans()` JavaScript helper which works like Laravel's PHP `trans()` helper to retrieve translation strings.

#### Examples

[](#examples-1)

import the `trans()` function like follow:

```
import { trans } from "matice";
```

Let's assume we have this translations file:

```
// resources/lang/en/custom.php

return [
    'greet' => [
        'me' => 'Hello!',
        'someone' => 'Hello :name!',
        'me_more' => 'Hello Ekcel Henrich!',
        'people' =>'Hello Ekcel!|Hello everyone!',
    ],
    'balance' => "{0} You're broke|[1000, 5000] a middle man|[1000000,*] You are awesome :name, :count Million Dollars"
];
```

```
// resources/lang/fr/custom.php

return [
    'greet' => [
        'me' => 'Bonjour!'
    ]
];
```

#### trans

[](#trans)

Retrieve a text:

```
let sentence = ''

sentence = trans('greet.me') // Hello!

// With parameters
sentence = trans('greet.someone', {args: {name: "Ekcel"}}) // Hello Ekcel!
```

#### Update locale

[](#update-locale)

Matice exposes `setLocale` function to change the locale that is used by the `trans` function.

```
import { setLocale } from "matice"

// update the locale
setLocale('fr')
const sentence = trans('greet.me') // Bonjour!
```

#### Pluralization

[](#pluralization)

On pluralization, the choice depends on the `count` argument. To activate pluralization pass the argument `pluralize` to true.

```
// Simple pluralization
sentence = trans('greet.people', {args: {count: 0}, pluralize: true}) // Hello Ekcel!
sentence = trans('greet.people', {args: {count: 2}, pluralize: true}) // Hello everyone!

// Advanced pluralization with range. Works the same way.
// [balance => '{0} You're broke|[1000, 5000] a middle man|[1000000,*] You are awesome :name, :count Million Dollars']
sentence = trans('balance', {args: {count: 0}, pluralize: true}) // You're broke
sentence = trans('balance', {args: {count: 3000}, pluralize: true}) // a middle man
```

#### Trans Choice

[](#trans-choice)

Matice provides a helper function for pluralization

```
import { transChoice } from "matice"

let sentence = transChoice('balance', 17433085, {name: 'Ekcel'}) // You are awesome Ekcel, 17433085 Million Dollars
```

#### Underscore function

[](#underscore-function)

- As well of the `trans()` function, Matice provide `__()` that does the same as the `trans()` function but with this particularity not to throw an error when the key is not found but returns the key itself.

`transChoice()` always throws an error if the key is not found. To change this behaviour, use `__(key, {pluralize: true})`

```
sentence = trans('greet.unknown') // -> throws an error with a message.
sentence = __('greet.unknown') // greet.unknown
```

#### Default values

[](#default-values)

Matice uses your current app locale `app()->getLocale()` as the default locale when generating the translation object with the blade directive `@translations`. Same applies when generating with command line.

When Matice does not find a key, it falls back to the default locale and search again. The fallback is the same you define in your `config.app.fallback_locale`.

```
// config/app.php

'locale' => 'fr',
'fallback_locale' => 'en',
```

#### Retrieve the current locale

[](#retrieve-the-current-locale)

Matice exposes the `MaticeLocalizationConfig` class :

```
import { MaticeLocalizationConfig } from "matice"

const locale = MaticeLocalizationConfig.locale // 'en'

const fallbackLocale = MaticeLocalizationConfig.fallbackLocale // 'en'

const locales = MaticeLocalizationConfig.locales // ['en', 'fr']
```

Matice also provides helpers to deal with locales information:

```
import { setLocale, getLocale, locales } from "matice"

// Update the locale
setLocale('fr') //

const locale = getLocale() // 'fr'

const locales = locales() // ['en', 'fr']
```

#### Force locale

[](#force-locale)

With the version 1.1.4, it is possible to force the locale for a specific translation WITHOUT changing the global local.

```
setLocale('en') // Set the current locale to English.

trans('greet.me') // "Hello!"
trans('greet.me', { locale: 'fr' }) // "Bonjour!"
trans('greet.me', { args: {}, locale: 'fr' }) // "Bonjour!"

__('greet.me', { locale: 'fr' }) // "Bonjour!"

transChoice('greet.me', 1, undefined, 'fr') // "Bonjour!"
transChoice('greet.me', 1, {}, 'fr') // "Bonjour!"
```

Filtering translations
----------------------

[](#filtering-translations)

Matice supports filtering the translations it makes available to your JavaScript, which is great to control the size of your data your translations become too large with thousands of lines.

#### Filtering namespaces

[](#filtering-namespaces)

To set up namespace translations filtering, update in your config file either an `only` or `except` setting as an array of translations folders or files. `Note: Setting the same namespace both 'only' and 'except' will result to 'except'. But in the other cases, 'only' takes precedence over 'except'`

```
    // config/matice.php

    return [
        // Export only
        'only' => [
            'fr/', // Take all the 'fr' directory with his children
            'es', // Take all the 'es' directory with his children
            'en/auth', // With or without the file extension
            'en/pagination.php',
            'en/validations',
        ],

        // Or... export everything except
        'except' => [
            'en/passwords',
            'en\\validations',
        ],
    ];
```

The base directory is the lang\_directory defined in the config file: `config('matice.lang_directory')`.

Use with SPA
------------

[](#use-with-spa)

Matice registers an Artisan console command to generate a `matice_translations.js` translations file, which can be used (or not) as part of an asset pipeline such as [Laravel Mix](https://laravel.com/docs/mix).

You can run `php artisan matice:generate --no-export` in your project to generate a static translations file without the export statement in `resources/assets/js/matice_translations.js`. You can customize the generation path in the `config/matice.php` file.

```
php artisan matice:generate --no-export
```

An example of `matice_translations.js`, where auth translations exist in `resources/lang/en/auth.php`:

```
// resources/lang/en/auth.php

return [
    'failed' => 'These credentials do not match our records.',
    'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];
```

```
// matice_translations.js

const Matice = {
    locale: 'en',
    fallbackLocale: 'en',
    translations: {
      en: {
        auth: {
          failed: 'These credentials do not match our records.',
          throttle: 'Too many login attempts. Please try again in :seconds seconds.'
        }
      }
    }
};
```

At this point you can use in javascript this translations file like usual, paste in your html as well.

This is useful if your laravel and js app are separated like with SPA or PWA. So you can link the generated translations file with your JS App. If you're not in the case of SPA, WPA... you might never have to generate the translations manually because `@translations` directive already does it for you when the app environment is 'production' to improve performance.

```

    😃

```

Whenever your translation messages change, run `php artisan matice:generate` again. Remember to disable browser cache, it may have cached the old translations file.

Using with Vue Components
-------------------------

[](#using-with-vue-components)

Basically, Matice can be integrated to any Javascript projects. Event with some big framework like Vue.js React.js or Angular. Some frameworks like Vue re-renders the UI dynamically. In this section we show you how to bind Matice with Vue 2. Based on this example we assume you can take inspiration to do the same with the framework you use for your project. For example, with React, you should re-render the whole app after `setLocale()` is called for the changes to be visible.

Add this to your `app.js` file:

```
// app.js

import {__, trans, setLocale, getLocale, transChoice, MaticeLocalizationConfig, locales} from "matice"

Vue.mixin({
    methods: {
        $trans: trans,
        $__: __,
        $transChoice: transChoice,
        $setLocale(locale: string) {
            setLocale(locale);
            this.$forceUpdate() // Refresh the vue instance(The whole app in case of SPA) after the locale changes.
        },
        // The current locale
        $locale() {
            return getLocale()
        },
        // A listing of the available locales
        $locales() {
            return locales()
        }
    },
})
```

Then you can use the methods in your Vue components like so:

```
{{ $trans('greet.me') }}
```

Dive Deeper
-----------

[](#dive-deeper)

Matice extends the Laravel `Translator` class. Use `Translator::list()` to return an array representation of all of your app translations.

If you want to load only translations of a specific locale, use the matice facade:

```
use GENL\Matice\Facades\Matice;

// Loads all the translations
$translations = Matice::translations();

// Or loads translations for a specific locale.
$translations = Matice::translations($locale);
```

**Environment-based loading of minified matice helper file**

When using the `@translations` Blade directive, Matice detects the current environment and minify the output if `APP_ENV` is `production`.

In development, `@translations` loops into the lang directory to generate the matice object each time the page reloads, and doesn't generate`matice_translations.js` file. In production, `@translations` generate the `matice_translations.js` file for you when your app is open for the first time then the generated file is used every time the page reloads. The Matice object is not generated every time, so it has no effect on performances in production. This behavior can be disabled in the `config/matice.php` file, set `use_generated_translations_file_in_prod` to false.

\######**Note: Matice supports json translation files as well as php files.**,

### Testing

[](#testing)

```
// --  laravel test --
composer test

// -- js test --

// With yarn
yarn test

// With npm
npm run test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [GENL](https://github.com/GENL/matice)
- [All Contributors](../../contributors)
- This package was largely inspired by [Ziggy](https://github.com/tighten/ziggy)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Laravel Package Boilerplate
---------------------------

[](#laravel-package-boilerplate)

This package was generated using the [Laravel Package Boilerplate](https://laravelpackageboilerplate.com).

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance40

Moderate activity, may be stable

Popularity51

Moderate usage in the ecosystem

Community25

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 52.5% 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 ~118 days

Recently: every ~71 days

Total

14

Last Release

494d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/fe67c0f9ce1ee8a696fd8289e69c64743ab39f31f4d8544412a0b2d37da375f9?d=identicon)[Ekcel Henrich](/maintainers/Ekcel%20Henrich)

---

Top Contributors

[![GENL](https://avatars.githubusercontent.com/u/36866702?v=4)](https://github.com/GENL "GENL (21 commits)")[![tortuetorche](https://avatars.githubusercontent.com/u/5038872?v=4)](https://github.com/tortuetorche "tortuetorche (8 commits)")[![gildastema](https://avatars.githubusercontent.com/u/19803232?v=4)](https://github.com/gildastema "gildastema (4 commits)")[![patrickomeara](https://avatars.githubusercontent.com/u/571773?v=4)](https://github.com/patrickomeara "patrickomeara (2 commits)")[![RocketC31](https://avatars.githubusercontent.com/u/87506281?v=4)](https://github.com/RocketC31 "RocketC31 (1 commits)")[![mgralikowski](https://avatars.githubusercontent.com/u/17027876?v=4)](https://github.com/mgralikowski "mgralikowski (1 commits)")[![matteogilioli](https://avatars.githubusercontent.com/u/55749040?v=4)](https://github.com/matteogilioli "matteogilioli (1 commits)")[![dualklip](https://avatars.githubusercontent.com/u/2706500?v=4)](https://github.com/dualklip "dualklip (1 commits)")[![redelschaap](https://avatars.githubusercontent.com/u/6915990?v=4)](https://github.com/redelschaap "redelschaap (1 commits)")

---

Tags

laraveltranslationsmatice

### Embed Badge

![Health badge](/badges/genl-matice/health.svg)

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

###  Alternatives

[vemcogroup/laravel-translation

Translation package for Laravel to scan for localisations and up/download to poeditor

135304.0k2](/packages/vemcogroup-laravel-translation)[statikbe/laravel-chained-translator

The Laravel Chained Translator can combine several translators that can override each others translations.

36149.4k6](/packages/statikbe-laravel-chained-translator)[vildanbina/laravel-auto-translation

A Laravel package for automating the translation of language files.

9220.5k2](/packages/vildanbina-laravel-auto-translation)[cactus-galaxy/filament-astrotomic

Filament support for Astrotomic's Laravel Translatable package.

2516.3k](/packages/cactus-galaxy-filament-astrotomic)[square-bit/laravel-pt-localization

Portuguese Localization package for Laravel

113.6k](/packages/square-bit-laravel-pt-localization)

PHPackages © 2026

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