PHP code example of fredckl / transable

1. Go to this page and download the library: Download fredckl/transable 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/ */

    

fredckl / transable example snippets


composer 

"providers" => [
    ...

    /*
     * Package Service Providers...
     */
    Fredckl\Transable\ServiceProvider::class,
    
    ...
]

php artisan migrate

php artisan vendor:publish --tag=transable


return [
    "default_locale" => "en", // Change if you your default locale is different
    "locales" => [
        "fr",
        "es",
        /// ...
    ]
];


namespace App;

use Fredckl\Transable\src\Traits\Transable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Transable; // Import Trait

    protected $fillable = ['title', 'content'];
    
    /**
     * Define fields translatable
     */
    public function transable (): array
    {
        return [
            'title', 
            'content'
        ];
    }
}

$post = App\Post::find(1);
echo $post->title; // return "Hello"
echo $post->content; // return "Content"
echo $post->fr->title; // return "Hello", default value EN because the value not exists

$post->fr->title = "Salut";
$post->fr->content = "contenu";
$post->es->title = "Hola";

$post->save(); true

echo $post->fr->title; // return "Salut"
echo $post->fr->content; // return "contenu"
echo $post->es->title; // return "Hola"  
echo $post->es->content; // return "Contents", default value EN because the value not exists

$data = [
    'title' => 'Hello',
    'content' => 'Contents',
    'fr' => [
        'title' => 'Salut',
        'content' => 'contenu'
    ],
    'es' => [
        'title' => 'Hola',
        'content' => 'contenido'
    ]
];
App\Post::create($data);

$post = App\Post::where('title', 'Hello')->first();
echo $post->fr->title; // return "Salut";

App::setLocale('fr');
App\Post::autoTranslate();
// OR without App::setLocale
App\Post::autoTranslate('fr');

$post = App\Post::where('title', 'Hello')->first();
echo $post->title; // return "Salut"

App\Post::translated(); // retrieve all posts translated
App\Post::doesntHaveTranslations(); // retrieve all posts without translations

App\Post::whereTranslation($field, $value); // return matched posts

$post->delete(); // delete post and all translations
App\Post::deleteTranslationsWhenEmptyModel(); delete all translations without model
// OR 
Fredckl\Transable\Models\I18n::deleteEmpty();