Laravel Multilingual Models

Overview

Laravel Multilingual Models

Make Eloquent model attributes translatable without separate database tables for translation values.

Simply access $country->name and you get a value based on your application's current locale.

$country->nameTranslations->en will be the value of a specific locale.

You can get all the translations of a given attributes with $country->nameTranslations->toArray().

Installation

Install the package through Composer:

composer require guidocella/laravel-multilingual

Then publish the config file:

php artisan vendor:publish

Usage

First make sure that the translatable attributes' field type is text or json. If you are building the database from a migration file you may do this:



Schema::create('countries', function (Blueprint $table)
{
	$table->increments('id');
	$table->json('name');
});

Now that you have the database ready to save a JSON string, add the Translatable trait to your models and a public array property $translatable that holds the names of the translatable fields.



class Country extends Model
{
    use GuidoCella\Multilingual\Translatable;

    public $translatable = ['name'];
}

The trait will override the getCasts method to instruct Eloquent to cast all $translatable attributes to array without having to specify them again in $casts.

Now that our model's name attribute is translatable, when creating a new model you may specify the name field as follows:



Country::create([
	'name' => [
		'en' => 'Spain',
		'es' => 'España'
	]
]);

It will be automatically converted to a JSON string and saved in the name field of the database. You can later retrieve the name like this:

$country->name

This will return the country name based on the current locale. If the translation in the current locale doesn't have a non-null value then the fallback_locale defined in the config file will be used.

In case nothing can be found null will be returned.

You may also want to return the value for a specific locale; you can do it using the following syntax:

$country->nameTranslations->en

This will return the English name of the country.

To return an array of all the available translations you may use:

$country->nameTranslations->toArray()

You can update the translation in a single locale with Eloquent's arrow syntax for JSON fields:

$country->update(['name->'.App::getLocale() => 'Spain']);

Validation

You can validate the presence of specific locales like so:



$validator = validator(
    ['name' => ['en' => 'One', 'es' => 'Uno']],
    ['name.en' => 'required']
);

However, this package includes the translatable_required validation rule for requiring that the translations are provided in every locale:



$validator = validator(
    ['name' => ['en' => 'One', 'es' => 'Uno']],
    ['name' => 'translatable_required']
);

You may define the available locales as well as the fallback_locale from the package config file.

Now you only need to add the translated message of our new validation rule: add this to the validation.php translation file:

'translatable_required' => 'The :attribute translations must be provided.',

Queries

Laravel lets you query JSON columns with the -> operator:

Company::where('name->en', 'Monsters Inc.')->first();

Country::orderBy('name->'.App::getLocale())->get();
You might also like...
Add Social Reactions to Laravel Eloquent Models. It lets people express how they feel about the content. Fully customizable Weighted Reaction System & Reaction Type System with Like, Dislike and any other custom emotion types. Do you react?
The package lets you generate TypeScript interfaces from your Laravel models.

Laravel TypeScript The package lets you generate TypeScript interfaces from your Laravel models. Introduction Say you have a model which has several p

A Laravel package for attachment files to models

Laravel attachmentable package A package for attachment files to models Installation Run the command below to add this package: composer require larav

A package to implement repository pattern for laravel models

Laravel Model UUID A simple package to use Repository Pattern approach for laravel models . Repository pattern Repositories are classes or components

Advanced Laravel models filtering capabilities

Advanced Laravel models filtering capabilities Installation You can install the package via composer: composer require pricecurrent/laravel-eloquent-f

A Laravel package making a diagram of your models, relations and the ability to build them with it
A Laravel package making a diagram of your models, relations and the ability to build them with it

Laravel Schematics This package allows you to make multiple diagrams of your Eloquent models and their relations. It will help building them providing

A Laravel Code Generator based on your Models using Blade Template Engine
A Laravel Code Generator based on your Models using Blade Template Engine

Laravel Code Generator is a PHP Laravel Package that uses Blade template engine to generate code for you. The difference between other code generators

Tag support for Laravel Eloquent models - Taggable Trait

Laravel Taggable Trait This package is not meant to handle javascript or html in any way. This package handles database storage and read/writes only.

Creates repositories for Laravel models

##Repositories Maker## Repository pattern is an abstraction layer for your models. Instead of writing tones of duplicated queries in your controllers.

Releases(v1.0.2)
Owner
Guido Cella
Guido Cella
Searches for multilingual phrases in Laravel project and automatically generates language files for you.

Laravel Lang Generator Searches for multilingual phrases in a Laravel project and automatically generates language files for you. You can search for n

Gleb 5 Oct 19, 2022
Get estimated read time of an article. Similar to medium.com's "x min read". Multilingual including right-to-left written languages. Supports JSON, Array and String output.

Read Time Calculates the read time of an article. Output string e.g: x min read or 5 minutes read. Features Multilingual translations support. Static

Waqar Ahmed 8 Dec 9, 2022
Trait for multilingual resource file support

⚡ Usage This library supports MultilingualResourceTrait which can be used in PluginBase. Multilingual support of resource files is possible using this

PocketMine-MP projects of PresentKim 1 Jun 7, 2022
Postgis extensions for laravel. Aims to make it easy to work with geometries from laravel models.

Laravel Wrapper for PostgreSQL's Geo-Extension Postgis Features Work with geometry classes instead of arrays. $model->myPoint = new Point(1,2); //lat

Max 340 Jan 6, 2023
Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel 5.

Laravel-Mediable Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel. Features Filesystem-driven appro

Plank Design 654 Dec 30, 2022
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.5k Jan 7, 2023
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.6k Dec 30, 2022
Record the change log from models in Laravel

This package will help you understand changes in your Eloquent models, by providing information about possible discrepancies and anomalies that could

Owen IT Services 2.5k Dec 30, 2022
Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Dwight Watson 955 Dec 25, 2022
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

cybercog 879 Dec 30, 2022