vershub/laraveltranslations is a Laravel package for laravel package for translatable models.
It currently has 0 GitHub stars and 64 downloads on Packagist (latest version v1.0.1).
Install it with composer require vershub/laraveltranslations.
Discover more Laravel packages by vershub
or browse all Laravel packages to compare alternatives.
Last updated
This lightweight Laravel package enables you to eager load models along with their translations in the specified language, efficiently preventing the N+1 query problem. Additionally, it allows you to retrieve a single translation (instead of an array) without unnecessarily loading extra models into memory..
Install the package via Composer:
composer require vershub/laraveltranslations
Extend the TranslatableModel class and implement the required abstract methods:
namespace App\Models;
use Vershub\LaravelTranslations\TranslatableModel;
class CarBrand extends TranslatableModel
{
protected $fillable = ['name'];
protected function getTranslationModel(): string
{
return CarBrandTranslation::class;
}
protected function getForeignKeyForTranslation(): string
{
return 'car_brand_id';
}
}
The translation model should be a standard Eloquent model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CarBrandTranslation extends Model
{
protected $fillable = ['locale_code', 'name', 'description'];
}
Example of translation table migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCarBrandTranslationsTable extends Migration
{
public function up()
{
Schema::create('car_brand_translations', function (Blueprint $table) {
$table->id();
$table->foreignId('car_brand_id')->constrained()->cascadeOnDelete();
$table->string('locale_code');
$table->string('name');
$table->text('description')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('car_brand_translations');
}
}
withTranslation Scopeuse App\Models\CarBrand;
$carBrands = CarBrand::withTranslation()->get();
foreach ($carBrands as $carBrand) {
echo $carBrand->translation->name;
}
use App\Models\CarBrand;
$carBrands = CarBrand::withTranslation('fr')->get();
foreach ($carBrands as $carBrand) {
echo $carBrand->translation->name;
}
use App\Models\CarBrand;
$carBrands = CarBrand::withTranslation('fr:id,locale_code,name,description')->get();
By default, the package uses locale_code. You can change this by publishing the config file and change the value of locale_code_column key:
return [
'locale_code_column' => 'locale_code'
];