PHP code example of msafadi / laravel-eloquent-l10n
1. Go to this page and download the library: Download msafadi/laravel-eloquent-l10n library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
msafadi / laravel-eloquent-l10n example snippets
// Laravel v11.x
// file: bootstrap/app.php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Safadi\Eloquent\L10n\EloquentL10nServiceProvider;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
// ...
->withProviders([
// ...
EloquentL10nServiceProvider::class
])
->create();
// Laravel 10.x and older
// file: config/app.php
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
EloquentL10nServiceProvider::class
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
// ...
])->toArray(),
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Safadi\Eloquent\L10n\Concerns\HasTranslationsModel;
use Safadi\Eloquent\L10n\Contracts\Translatable;
class Post extends Model implements Translatable
{
use HasTranslationsModel;
}
// Use the current application locale
$post = Post::find(1);
$translatedTitle = $post->title;
// Specify the locale manually
$post = Post::useLocale('ar')->find(1);
$translatedTitle = $post->title;
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Safadi\Eloquent\L10n\Concerns\\HasTranslatableAttributes;
use Safadi\Eloquent\L10n\Contracts\Translatable;
class Post extends Model implements Translatable
{
use HasTranslatableAttributes;
public function translatableAttributes(): array
{
return ['title', 'content']; // Specify translatable attributes
}
}
$post = Post::find(1);
// Get title translated with the current application locale
$translatedTitle = $post->title;
// Get title translated with the specified locale
$translatedTitle = $post->setLocale('ar')->title;
$post = Post::create([
'status' => 'published',
'author' => 'Mohammed',
// ...,
'title' => [
'en' => 'Post Title',
'ar' => 'عنوان المنشور',
// ...
],
'content' => [
'en' => 'Post content',
'ar' => 'محتوى المنشور',
// ...
],
]);
//
$post = new Post();
// Set all translations at once
$post->title = [
'en' => 'Post Title',
'ar' => 'عنوان المنشور',
// ...
];
$post->save();
// Update partial translations
$post = Post::find(1);
// Update title in the current application locale, keep other translations without change.
$post->title = 'English';
// Specify the translation locale.
// This will update the `ar` translation and keep other translations without change.
$post->setLocale('ar')->content = 'عربي';
// ...
$post->save();