Adding i18n to Laravel and Filament application
Recently, I created this personal website to showcase my profile, work, and side projects. The primary language of the site is English. However, I also want to be accessible to Spanish speakers, which is why I created this blog for both English and Spanish audiences.
Filament Configuration
I'm using the TALL stack (Tailwind CSS + Alpine.js + Laravel + Livewire) and Filament for content management. While there's a package from Spatie called spatie-translatable, since we’re using Filament, I chose the filament-spatie-translatable plugin instead.
After following the plugin setup steps, we can create content in multiple languages. For example, here’s my Article model. As you can see, I use the trait from the package and specify the columns to be translated.
So, when you are gonna create an article using Filament, you will something like this.There's a dropdown in the header where you can add content for each language specified in the provider. After saving the record, the translated values for each language are stored in JSON format in the database.
Using Translatable Content
Using blade we show the content like this.
Laravel will automatically use the language you have set in your .env configuration file.
Changing Languages
What if we want to let users choose their preferred language? In this case, we need to store the selected language in the session and create middleware that checks for the language selection before redirecting to any routes.
The middleware will look like this:
then, we create a route for storing in session the language specified in the url parameter.Finally, we add a button to change the language. Since I have only two languages (English and Spanish), I created a simple conditional statement:and that's all!