PHP code example of rat.md / laravel-translatable

1. Go to this page and download the library: Download rat.md/laravel-translatable 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/ */

    

rat.md / laravel-translatable example snippets


use Rat\Translatable\Concerns\Translatable;

class Post extends Model
{
    use Translatable;

    protected $fillable = ['title', 'content', 'tags'];
    protected $translatable = ['title', 'content', 'tags'];
    protected $casts = [
        'tags' => 'array'
    ];
}

// Mass assignment
Post::create([
    'title' => [
        'en' => 'Hello World',
        'de' => 'Hallo Welt',
    ]
]);

// Manual assignment
$post = new Post;
$post->title = 'Hello World';
$post->setTranslation('de', 'title', 'Hallo Welt');
$post->save();

// Manual assignment using withLocale()
$post = new Post;
$post->title = 'Hello World';
$post->withLocale('de', function ($model) {
    $model->title = 'Hallo Welt';
});

$post = Post::first();

// Direct access based on app()->getLocale()
echo $post->title;
app()->setLocale('de');
echo $post->title;

// Manual access
echo $post->getTranslation('de', 'title');
echo $post->getTranslations('de')['title'];

// Access by mutating model locale
$post->locale('de');
echo $post->title;

// Access by cloning model with desired locale
echo $post->in('de')->title;

// Access by using withLocale()
$post->withLocale('de', function ($model) {
    echo $model->title;
});

Post::whereLocale('de', 'title', 'Hallo Welt')->get();
Post::query()->whereLocale('de', 'title', 'Hallo Welt')->get();

Post::whereHasLocale('de')->get();
Post::whereMissingLocale('de')->get(); // or "whereDoesntHaveLocale"

Post::orderByLocale('de', 'title', 'ASC')->get();
bash
php artisan vendor:publish --tag="laravel-translatable-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-translatable-config"