Building a Laravel Translation Package – Wrangling Translations

Published on by

Building a Laravel Translation Package – Wrangling Translations image

As we’ve discussed earlier in the series, out of the box, Laravel translations are stored in language files. These can be either PHP array-style syntax or straight up JSON files.

The Laravel Translation package interacts with the files in order to achieve the following:

  • List all languages
  • Add a language
  • List all translations
  • Add a translation
  • Update existing translations

The plan for the package is, much like many features of Laravel, to expose multiple drivers to power the translation management. The first driver will utilize Laravel’s existing file-based translations with plans to later add a database driver. With this in mind, we first define a contract to which driver will implement to ensure all the required methods are available to the package.

The file driver needs to interrogate the filesystem in order to return the data in the required format. This involves a lot of filtering, mapping and iterating, so we will lean quite heavily on Laravel’s collections.

Listing languages

To generate a collection of languages, we use the filesystem to get an array of directories from the configured language path, wrapping the result in a collection.

$directories = Collection::make($this->disk->directories($this->languageFilesPath));

Next, we utilize the mapWithKeys function to iterate over the directories, stripping the language from the path (it will be the last segment) and returning a key => value array.

return $directories->mapWithKeys(function ($directory) {
$language = basename($directory);
return [$language => $language];
});

The result looks something like this:

// $this->allLanguages()->toArray();
 
[
‘en’ => ‘en’,
‘fr’ => ‘fr’,
‘es’ => ‘es’,
];

Adding languages

To create a new language, we need to add a new directory and empty JSON file to the configured language path and name it after the language we’re adding.

$this->disk->makeDirectory(“{$this->languageFilesPath}/$language”);
 
if (! $this->disk->exists(“{$this->languageFilesPath}/{$language}.json”)) {
$this->disk->put(
“{$this->languageFilesPath}/$language.json”,
json_encode((object) [], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
);
}

Then, we use the filesystem to add a new file to the language path containing an empty JSON encoded array.

Using the JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT constants ensure the generated JSON is in the right format.

Listing translations

When listing translations we want to ensure we differentiate the group (array style) translations from the single (JSON style).

Group To get the group translations, we can use the filesystem to get all the files from the language directory.

$groups Collection($this->disk->allFiles(“{$this->languageFilesPath}/{$language}“));

Then, to get the translations, we can iterate over all the files in the directory and use the filesystem’s getRequire method to require the file giving us direct access to the array.

$groups->mapWithKeys(function ($group) {
return [$group->getBasename(‘.php’) => $this->disk->getRequire($group->getPathname())];
});

The result looks something like this:

[
‘auth’ => [
‘failed’ => ‘These credentials do not match our records’,
],
]

Single

We can get the single translations by using json_decode on the contents of the file.

if ($this->disk->exists($this->languageFilesPath.“/$language.json”)) {
return new Collection(json_decode($this->disk->get($singlePath), true));
}

The result looks something like this:

[
‘hello’ => ‘hello’,
]

Adding/updating translations

Translations are added and updated in largely the same fashion. First, we get the contents of the file the translation should be added to in array format. Then, we check whether or not the key to be added already exists. If it does, we update the value and if not, we append the new key and value to the array. Finally, the whole array is written back to the file.

Group

$translations = $this->getGroupTranslationsFor($language);
$values = $translations->get($group);
$values[$key] = $value;
$translations->put($group, $values);
$this->disk->put(
“{$this->languageFilesPath}/{$language}/{$group}.php”,
“<?php\n\nreturn “.var_export($translations, true).‘;’.\PHP_EOL
);

Single

$translations = $this->getSingleTranslationsFor($language);
$translations->put($key, $value);
$this->disk->put(
“{$this->languageFilesPath}/$language.json”,
json_encode((object) $translations, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
);

Some of the code samples have been truncated for clarity. You can see the full code for the files mentioned in the article below:

Driver Interface File Driver

This driver lays the foundation from which we can build upon. Next time, we’ll build out the user interface which will ship with the package. It utilizes a combination of Tailwind CSS and Vue.js, two frameworks which have been widely adopted by the Laravel community.

Joe Dixon photo

Founder and CTO of ubisend. Proud Father to two tiny heroes, Husband, developer, occasional globetrotter.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article