Multilanguage
Introduction
Thanks to the spatie/laravel-translatable package you can translate your models into multiple languages. HotCoffee's own Article and InfoPage models take advantage of this. Additionally there is a helper method language_fields() that will generate the HTML input fields in your forms in separate tabs on the page for each language that you declare in hotcoffee.php config file.
Usage
Define all the locales for the translatable models in the languages array in config/hotcoffee.php. Each language should be an associative array with this structure'acronym' => 'full name'. The first language is going to be the default one.
'languages' => [
'en' => 'English',
'bg' => 'Български',
'de' => 'Deutsche',
],If you have defined more than one language in the array you will be able to see the flag icons above the title and content fields when creating or editing info pages and articles. Clicking an icon will switch to the tab that contains the fields for that particular locale.

These fields and flag icons are generated, because we called the language_fields() helper method in the template. Flag images are loaded from the public/vendor/hotcoffee/img/flags directory. If the acronym of a locale is 'de', then the loaded image will be de.svg from that same directory. Simply put any missing flag svg files that you need there.
To make your own models translatable they should use the Spatie\Translatable\HasTranslations trait. You need to also define all translatable fields:
Now in your template:
The HTML output of language_fields() method in this case would look something like this (given, that we have set 3 locales - en, bg and de):
The function will also add "has-danger" class if a validation of a field has failed.

It will also populate the value="" attribute (or content of a <textarea> field) automatically when editing a model. Hence why you need to specify the variable name of the model as a second parameter:
When the form is submitted, the content of the request will be this:

Now in your store() method you can do this:
Of course when using Eloquent's create() or update() methods you will need to specify the fillable or guarded attribute on the model.
Whenever you need to display the content of the product for example you can just do this:
If you want to get the content field in a specific locale:
To learn more about translating models visit https://github.com/spatie/laravel-translatable
Last updated