In this episode, we're focusing on making all of our translations available on the client side when using Inertia in a Laravel project. Translations are stored in files on the backend, but we need a way to get just the current language's translations over to the front-end, so our JavaScript components can easily use them.
We start by setting up our translation files (including a new German one), and then work through reading these from the lang
directory based on which locale is selected. We want translations to come through in dot notation like auth.failed
, so if there are keys with the same name in different files, we can still tell them apart. This means we have to process the files a bit, turning nested arrays into a flattened structure with proper prefixes.
To do this, we build a collection in Laravel by grabbing all language files for the selected locale, reading their contents, and transforming them into the right format. We even handle extra edge cases, like making sure file extensions don't sneak into our prefixes, and keeping it dynamic in case we add JSON-based translations later.
Once that's in place, all translations for the selected language are shared with Inertia, so they're accessible in our front-end components. To wrap up, we write a test to check that our translations are included, in the right structure, whenever we render a page — so we can be confident that our setup works smoothly!
Next time, we'll look at caching this so it's more efficient, but for now, we've laid the groundwork for sharing translations between Laravel and Inertia.