Code Monkey home page Code Monkey logo

laravel-translatable's Introduction

Introduction

Latest Version MIT License Offset Earth Larabelles

GitHub Workflow Status GitHub Workflow Status Codecov Coverage Total Downloads GitBook

laravel-translatable socialcard

If you want to store translations of your models into the database, this package is for you.

This is a Laravel package for translatable models. Its goal is to remove the complexity in retrieving and storing multilingual model instances. With this package you write less code, as the translations are being fetched/saved when you fetch/save your instance.

The full documentation can be found at GitBook.

Installation

composer require astrotomic/laravel-translatable

Quick Example

Getting translated attributes

$post = Post::first();
echo $post->translate('en')->title; // My first post

App::setLocale('en');
echo $post->title; // My first post

App::setLocale('de');
echo $post->title; // Mein erster Post

Saving translated attributes

$post = Post::first();
echo $post->translate('en')->title; // My first post

$post->translate('en')->title = 'My cool post';
$post->save();

$post = Post::first();
echo $post->translate('en')->title; // My cool post

Filling multiple translations

$data = [
  'author' => 'Gummibeer',
  'en' => ['title' => 'My first post'],
  'fr' => ['title' => 'Mon premier post'],
];
$post = Post::create($data);

echo $post->translate('fr')->title; // Mon premier post

Tutorials

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details. You could also be interested in CODE OF CONDUCT.

Security

If you discover any security related issues, please check SECURITY for steps to report it.

Credits

Versions

Package Laravel PHP
v11.13 - v11.13 9.* / 10.* / 11.* ^8.0
v11.12 - v11.12 8.* / 9.* / 10.* ^8.0
v11.10 - v11.11 8.* / 9.* ^8.0
v11.6 - v11.9 5.8.* / 6.* / 7.* / 8.* >=7.2
v11.4 - v11.5 5.6.* / 5.7.* / 5.8.* / 6.* >=7.1.3
v11.0 - v11.3 5.6.* / 5.7.* / 5.8.* >=7.1.3

Treeware

You're free to use this package, but if it makes it to your production environment I would highly appreciate you buying the world a tree.

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you contribute to my forest you’ll be creating employment for local families and restoring wildlife habitats.

You can buy trees at offset.earth/treeware

Read more about Treeware at treeware.earth

laravel-translatable's People

Contributors

actuallymab avatar ahmed-aliraqi avatar askello avatar ben-nsng avatar caneco avatar cbl avatar chrillep avatar deargonaut avatar dependabot[bot] avatar derekmd avatar dimsav avatar easteregg avatar flyos avatar github-actions[bot] avatar gummibeer avatar hyleeh avatar johannesschobel avatar lan0 avatar laravel-shift avatar lloople avatar netdown avatar oleksandr-moik avatar plmarcelo avatar prime-hacker avatar rb1193 avatar sdebacker avatar sebastiandedeyne avatar shadowalker89 avatar tintamarre avatar yakidahan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-translatable's Issues

Replace fallback locale configuration and logic by dedicated Strategy class

The fallback logic should get moved out of the trait into dedicated class(es) which could be easily replaced by custom user logic without adjusting the whole trait.
It should be possible to chain multiple strategies to handle the current state but in multiple classes.

'fallback_strategies' => [
    LocaleStrategy::class => [
        'locale' => 'en',
    ],
    CountryLocaleStrategy::class,
    FirstDefinedLocaleStrategy::class,
],

A strategy instance should be created via DIC - this way an instance could also be bound, possible required injections will be done and custom arguments could be passed via an array like for LocaleStrategy.
The signature of called method should retrieve a lot of arguments to also handle model aware logic, attribute specific fallback and so on.

$strategy->fallback(
    Model $model,
    string $currentLocale,
    Collection $alreadyCheckedLocales,
    ?string $attribute = null,
): ?Model;

The method should return an instance of the translatable model or throw an exception FallbackNotFound which contains all checked locales null.
Every checked locale should be pushed to the collection. This way we can pass all already checked locales to the following strategies and prevent duplicated checks.

How to check if translatable title is nullable in data base

Models: Post, PostTranslatable
Let's say i have 3 localizations: 'en', 'ru', 'fr'
'en' title is 'Some title'
'ru' title is 'Заголовок'
'fr' title is '(empty)'
and if i go to localhost/fr/posts i see empty title but tied styles are still there(:
How can i check if posts->title (fr) or other languages are null and hide images, styles from PostModel

Pls any help

Get translations of many rows returned by Eloquent

How to get translations for many rows retrieved by eloquent queries with one or few database queries? If there is no translation for some of these rows the default fallback to be used.
Example: SomeModel::all();
The problem is that I can translate one row at a time using the ->translate($locale) method but if you do that in php loop it will generate n+1 (where n is the number of rows to be translated) queries to the database which is not efficient.

how to translate all the rows at one time

$categories = Category::all();

I want it to return

{
    "success":true,
    "data":[
        {
            "id":21,
            "category_id":2,
            "locale":"en",
            "name":"cat1",
            "details":"detials1",
            "image":"image1"
        }
    ]
}

for all the rows not like this

{
    "success":true,
    "data":[
        {
            "id":2,
            "created_at":null,
            "updated_at":null,
            "deleted_at":null,
            "name":"cat1",
            "translations":[
                {
                    "id":21,
                    "category_id":2,
                    "locale":"en",
                    "name":"cat1",
                    "details":"detials1",
                    "image":"image1"
                }
            ]
        }
    ]
}

with out translation object

Validation

Hello,

I'm a newbie inLaravel. I have tried to create a form request and add this in rules():

return $rules = [
    'translations.%name%' => 'required|string',
];

however it did not work.

This is my array:

translation.en.name
translation.de.name
translation.fr.name

So, my question is how to validate with this?

Thank you.

How to get all translations regardless of current locale?

I'm building an admin panel and need to get all translated values (in 3 different languages) on the same page regardless of the current set locale.

An example of
{{$news->title}}
works fine and displays value in current set locale as expected.

But i need to display values in all 3 languages on the same instance.

I tried something like below when current language is set to 'en':
{{$news->translate('de')->title}} //In order to get German translation

but it gives the error below:
Trying to get property 'title' of non-object....

How can i get the values in all languages?

laravel 6 support

Are you planning to add support for version 6. When to wait for these changes?

Thanks.

RuleFactory doesn't parse the array value

I am trying to validate require_with content key with all locales is replaced fine but values doesn't get replaced.

$rules = [
    'title' => 'required',
    '%content%' => "required_with:%title%,%description%",
    'en.content' => 'required', //make default locale required.
];
$rules = RuleFactory::make($rules, RuleFactory::FORMAT_ARRAY );

Output is:

array:3 [
  "title" => "required"
  "en.content" => "required"
  "fr.content" => "required_with:%icon%,%title%,%description%"
]

RuleFactory doesn't parse the array value? or am i missing something?

the locale is 'en' but the translation comes 'ar'

Describe the bug
I removed dimsav/laravel-translatable using the steps you mention here
replaced Dimsav\ by Astrotomic\ in my whole project
but when I change the locale to en every static translations on page comes en but the dynamic translations comes from the database comes ar.

To Reproduce
Here is an example of my code
Model

use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Astrotomic\Translatable\Translatable;

class ProductCategory extends Model implements TranslatableContract {
	use Translatable;
	public $translatedAttributes = [ 'name' ];
	protected $fillable = [ 'image', 'soft_delete' ];
}

Controller

public function menu() {
		$categories = ( new ProductCategory )
			->translatedIn( 'en' )
			->where( 'soft_delete', 0 )->with( 'categoryProduct' )
			->whereHas( 'categoryProduct', function ( $query ) {
				$query->where( 'product_category_id', '!=', null )
				->where( 'soft_delete', 0 );
			} )
			->withCount( 'categoryProduct' )
			->orderBy( 'sort_categories', 'ASC' )
			->orderBy( 'category_product_count', 'desc' )
			->get();
		return $categories;
	}

Migrations

Schema::create( 'product_category_translations', function ( Blueprint $table ) {
			$table->increments( 'id' );
			$table->integer( 'product_category_id' )->unsigned();
			$table->string( 'name', 255 );
			$table->string( 'locale' )->index();
			$table->unique( [ 'product_category_id', 'locale' ] );
			$table->foreign( 'product_category_id' )->references( 'id' )->on( 'product_categories' )->onDelete( 'cascade' );
		} );

Expected behavior
I should see the translation coming from database en

Versions (please complete the following information)

  • PHP: 7.3.5
  • Database: 5.7
  • Laravel: 5.8
  • Package: "astrotomic/laravel-translatable": "^11.1"

Exception
No thrown exception message.

Return value of App\Post::locale() must be of the type string, null returned

Describe the bug
just upgraded from dimsav to astrotomic everything used to work fine but now i'm getting this error : Return value of App\Post::locale() must be of the type string, null returned at vendor\astrotomic\laravel-translatable\src\Translatable\Translatable.php

To Reproduce
retrieving adding updating

Screenshot
Annotation 2019-06-22 004247

Versions (please complete the following information):

  • PHP: 7.3.6
  • Database: Mysql 8.0.16
  • Laravel: 5.8.24
  • Package: v11.1.0

Using translateOrNew() in an observer

I want to translate the $translatedAttributes of a model automatically with google translator. So I created a Observer because I have many models.

/**
 * Handle the model "updating" event.
 *
 * @param  \App\Model  $model
 * @return void
 */
public function updating(Model $model)
{
    $supportedLocales = \LaravelLocalization::getSupportedLocales();

    foreach ($supportedLocales as $localeCode => $properties) {
        foreach ($model->translatedAttributes as $key => $field) {
            // Google Translator magic HERE!
            $model->translateOrNew($localeCode)->{$field} = request()->{$field}[$localeCode];
        }
    }

   // save the translations
}

I have to save the model in updating() because I used translateOrNew(). If I use $model->save() I got a loop because of the observer.

How can I save model?

Translated columns sets to null values while using Query Builder

Describe the bug
I am making a Query with Joins . When I want to response translated columns in API they converting to null values.When I hide $translatedAttributes in the model everything works well. Or selecting the columns with an alias for example name as n it returns the value.
To Reproduce
My Database Schema
pages table:

Schema::create('pages', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->string('slug');
          $table->integer('status');
           $table->string('type')->nullable();
          $table->timestamps();
      });

page_translations table:

   Schema::create('page_translations', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('page_id')->unsigned()->index();
            $table->foreign('page_id')->references('id')->on('pages')->onDelete('cascade');
            $table->string('locale');
            $table->string('name');
            $table->longText('text');
            $table->timestamps();
        });

My Page Model:

class Page extends Model
{
    use \Astrotomic\Translatable\Translatable;
    
    public $translatedAttributes = ['name','text'];
    protected  $fillable = ['slug','status'];

    public function page_meta()
    {
        return $this->hasMany('App\Models\Page\PageMeta');
    }

    public function getDocumentLinkAttribute()
    {
        return $this->page_meta()->first()->meta_value;
    }
}

PageTranslations model class


PageTranslation extends Model
{
   public $timestamps=false;

   protected $fillable = ['name','text','status'];
}

My codes :

    protected  $pageModel;

    public function __construct(Page $page)
    {
        $this->pageModel = $page;
    }

    public function getApiWithType($type)
    {
        return $this->pageModel->leftJoin('page_translations','pages.id','=','page_translations.page_id')->where('page_translations.locale','az')->where('pages.type','page')->get();
    }

Expected behavior
I am making a Query with Joins. When I want to response translated columns in API they converting to null values.When I hide $translatedAttributes in the model everything works well. Or selecting the columns with an alias for example name as n it returns the true value.

Versions

  • PHP: 7.2.11
  • Database: Mysql
  • Laravel: 5.8
  • Package:

Scope whereTranslationLike case insensitive variant for PostgreSQL needed?

Hello

We use PostgreSQL and would need a case insensitive variant (i.e. ILIKE) of the whereTranslationLike scope, or a similar alternative.

Basically:

public function scopeOrWhereTranslationILike(Builder $query, string $translationField, $value, ?string $locale = null)
{
    return $this->scopeWhereTranslation($query, $translationField, $value, $locale, 'orWhereHas', 'ILIKE');
}

which works great. Is there an easy way to "attach" this to the package, that would also make it update-proof? So either for everbody in the next release or somewhere in our Laravel installation outside the vendor-directory?

I tried to use the LOWER(xxx) instead, but this resulted in

product_translations.LOWER(name)

which obviously doesn't work.

Love the package, btw! Switch to Astrotomic was easy as pie.

update method visibility and remove deprecated

Please comment if you have a reason why the method should stay public and be added to the public API.

visibility:

  • \Astrotomic\Translatable\Translatable::getLocaleKey
  • \Astrotomic\Translatable\Traits\Relationship::getTranslationModelName
  • \Astrotomic\Translatable\Traits\Relationship::getTranslationModelNameDefault
  • \Astrotomic\Translatable\Traits\Relationship::getTranslationModelNamespace
  • \Astrotomic\Translatable\Traits\Relationship::getTranslationRelationKey

deprecated:

  • \Astrotomic\Translatable\Traits\Relationship::getRelationKey

How to fetch all Model objects which are translated to a specific language?

I'm using Twill CMS, which uses the previous version of this package to translate models. (dimsav/translatable), however it's read only.

I have a multilingual website with a blog page that shows all my posts. However, if a blog post isn't translated (yet) to the current locale of the visitor, it just shows an empty post card without any content.

So how do I fetch all Posts that are translated to the current locale? Let's say my current locale is Spanish, I'd like to only show posts that are translated in the spanish language.

Field with null value gets data from other language field.

I have a NewsItems table as follows

Screenshot 2019-09-24 at 14 31 45

The issue here is that when I go to the show method of the NewsItem on the 'en' website, it's showing me the body content of the 'nl' row.
Once I add some data in the 'en' row's body, it's fine,

but when it's set to null, it's showing data from another translation
Is there any way to fix this?

Create models in seeders

In the docs and in Sep tutorial the translations are saved using new () and save ()
What about create ()??
I use Company::create ($attributes) but it saved only the default locale

Additional Data in "translation" table.

Is it possible to save some additional data in translate table?

Route::get('demo', function() {
    $page = new App\Page();
    $page->post_type = 'page';
    $page->published = true;
    $page->save();

    foreach (['en', 'nl', 'fr', 'de'] as $locale) {
        $page->user_id = 12;
        $page->translateOrNew($locale)->slug = str_slug("Title {$locale}");
        $page->translateOrNew($locale)->title = "Title {$locale}";
        $page->translateOrNew($locale)->meta_title = "Title {$locale}";
        $page->translateOrNew($locale)->meta_description = "Title {$locale}";
        $page->translate_published = true;
    }
    $page->save();

    echo 'Created an article with some translations!';
});

I am trying to add an option to make translation published or draft and maybe some fields?

I tried creating protected $fillable object in "PageTranslation" modal. But it always try to save everything in pages table

A tip to make translations for a Pivot Model

After an instance of Pivot Model is saved, it's attributes does not add id, because

// Illuminate\Database\Eloquent\Model

if ($this->getIncrementing()) {
    $this->insertAndSetId($query, $attributes);
}

And

// Illuminate\Database\Eloquent\Relations\Pivot

public $incrementing = false;

If id not added into attributes, laravel-translatable can not insert translations data properly.

So, to make translations for a Pivot Model, add this to this Model

public $incrementing = true;

Saving translated locale attributes

I try to save: $slider = Slider::create($input); with $input:

array:6 [▼
  "_token" => "6EReMQzWYsPg8Snwc2dfcvsvj1Yn08cTw51dFiWi"
  "title" => "we"
  "content" => "asd"
  "status" => "1"
  "locale" => "vi"
  "image" => "/images/slider/slide-5826879d561ba54aa8e7a788569832e85486308b.png"
]

but it save default locale(en). How i can solve it? Thank you!
Here's my database:
image

When I use toArray(), the default language is always returnd

Hi there,

I m following the following structure in order to handle destinations data. Every is working fine but when it comes to using toArray() method always return the default language

App\Models\Destination

use Astrotomic\Translatable\Translatable;
use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Illuminate\Database\Eloquent\Model;

class Destination extends Model implements TranslatableContract
{
    use Translatable;

    protected $table = 'destinations';

    public $translatedAttributes = ['name', 'excerpt', 'description'];

    protected $fillable = [
        'status',
        'layer_id',
        'map',
    ];
}

App\Models\DestinationTranslation

use Illuminate\Database\Eloquent\Model;

class DestinationTranslation extends Model
{
    protected $table = 'destination_translations';

    public $timestamps = false;

    protected $fillable = [
        'name',
        'excerpt',
        'description',
    ];
}

Query results when I use:

app()->setLocale('ru');
Destination::get()->toArray();
0 => array:16 [▼
    "id" => 1
    "status" => 1
    "slug" => "europe"
    "layer_id" => 1
    "_lft" => 1
    "_rgt" => 24
    "parent_id" => null
    "map" => null
    "created_at" => "2019-02-12 15:10:43"
    "updated_at" => "2019-02-19 14:42:04"
    "depth" => 0
    "name" => "Europe"
    "excerpt" => null
    "description" => null
    "destination_layer" => array:2 [▼
      "id" => 1
      "name" => "Continent"
    ]
    "translations" => array:2 [▼
      0 => array:6 [▼
        "id" => 1
        "destination_id" => 1
        "name" => "Europe"
        "excerpt" => null
        "description" => null
        "locale" => "en"
      ]
      1 => array:6 [▼
        "id" => 15
        "destination_id" => 1
        "name" => "Европа"
        "excerpt" => null
        "description" => null
        "locale" => "ru"
      ]
    ]
  ]

Thanks in advance

How do we migrate from dimsav/laravel-translatable to Astrotomic/laravel-translatable?

Hi,

Thanks for taking over the project!

I've checked the readme but don't see any info about how to switch over to this new repo/package for existing projects.

My guess is that I have to

  1. composer require this new package
  2. composer remove the old one
  3. update all namespaces that refer to the old package to the new one

Is there anything else I need to look out for?

Regards,
Erik

Optimize/Refactor test suite

  • upgrade test code base to current standard #73
  • optimize test classes performance and readability
    • LocalesTest #77
    • ScopesTest #86
    • TestCoreModelExtension #87
    • TranslatableTest #84
    • ValidationTest #88
  • Remove temp TestsBase class #81
  • Remove tests/seeds folder #89
  • reduce amount of models to the absolute minimum #101
  • use namespace Astrotomic\Translatable\Tests for tests #100
  • use static:: instead of $this-> for assertions #91
  • set void return type for all test methods #92
  • move to TravisCI instead of CircleCI #83
  • use sqlite in local environment (default) use MySQL in CI #83
  • Add @Lloople to package credits #82

orderByTranslation scope seems to ignore fallback locale

Describe the bug
orderByTranslation scope seems to ignore fallback locale.

To Reproduce

  • Save model translation to 'fr'
  • List models in 'fr' using orderByTranslation: list is OK
  • Use app()->setLocale('en')
  • List models in 'en' using orderByTranslation: list is empty (assuming no model was ever translated to en)

I'm supposed to write mostly in French, but some articles in English. As such, my main locale as well as my fallback_locale both are 'fr' in Laravel's config. In config/translatable.php, I set locale to null, use_fallback to true, use_property_fallback to true, and fallback_locale to null.

Expected behavior
In the absence of translation in English, I would expect orderByTranslation to return the expected list with the French translations available, instead of nothing at all (still assuming I have only French Translations in my database at the moment).

Versions (please complete the following information)

  • PHP: 7.3.9
  • Database: MariaDB 10.3.17
  • Laravel: 6.1.0
  • Package: 11.5

Sort with translation value and without translation value

Is your feature request related to a problem? Please describe.
I am using scopeOrderByTranslation when i try to order some data that has translation.
I also need to order data from the basic table.
When i try to sort with an element that doesn't exists to translations table and is only exists in basic table i get an error because in scopeOrderByTranslation method, in file Scopes.php line:64, (->orderBy($translationTable.'.'.$translationField) it add the translation table before the element.

Describe the solution you'd like
I would like to be able to order values from basic & translation table

Describe alternatives you've considered
I have created one method that i have delete the prefix of sorted value and it seems to work fine for translated and basic model values.
This is the method:

    public function scopeOrderByTranslationOrNot(Builder $query, string $translationField, string $sortMethod = 'asc')
    {
        $translationTable = $this->getTranslationsTable();
        $localeKey = $this->getLocaleKey();
        $table = $this->getTable();
        $keyName = $this->getKeyName();

        return $query
            ->join($translationTable, function (JoinClause $join) use ($translationTable, $localeKey, $table, $keyName) {
                $join
                    ->on($translationTable.'.'.$this->getTranslationRelationKey(), '=', $table.'.'.$keyName)
                    ->where($translationTable.'.'.$localeKey, $this->locale());
            })
            ->orderBy($translationField, $sortMethod)
            ->select($table.'.*')
            ->with('translations');
    }    

Do you think that this is an acceptable solution?

SyncTranslations Method on Update

Is there a method to Sync Translations on update?

I have one form for all languages and I want to sync all translations when user make changes. Lets say in the new edit French fields were removed/cleared so in this case sync should remove French entry instead of saving null/blank.

Polymorphic Relationships

#60

Sorry i got busy with different stuff.

So this is the structure i have that i am converting with this package:

Schema::create('posts', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->charset = 'utf8';
            $table->collation = 'utf8_unicode_ci';
            $table->bigIncrements('id');
            $table->unsignedBigInteger('author_id')->index()->unsigned();
            $table->enum('visibility', ['public', 'link', 'private'])->index();
            $table->boolean('translations')->default(0);
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('author_id')->references('id')->on('users')->onDelete('cascade');
});

Schema::create('post_translations', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->charset = 'utf8';
            $table->collation = 'utf8_unicode_ci';
            $table->bigIncrements('id');
            $table->string('locale')->index();
            $table->unsignedBigInteger('post_id');
            $table->morphs('postable');
            $table->string('post_key');
            $table->text('post_value');
            $table->unique(['post_id', 'locale', 'post_key']);

            $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});
//i know i probably don't need the post_id because i am using morph.

class Post extends Model
{
    use Translatable;

    protected $table = 'posts';
    public $translationForeignKey = 'post_id';

    public $translatedAttributes =['locale', 'post_id', 'postable_type',  'postable_id', 'post_key', 'post_value'];
    protected $fillable = ['author_id', 'visibility', 'translations'];

    public function settings()
    {
        return $this->morphMany(PostTranslation::class, 'postable');
    }
}

class PostTranslation extends Model
{
    public $timestamps = false;

    protected $table = 'post_translations';

    protected $fillable = ['locale', 'post_id', 'postable_type',  'postable_id', 'post_key', 'post_value'];

    public function postable()
    {
        return $this->morphTo();
    }
}

How can i use this polymorphic relation? there are multiple entry points for each post which i am saving in key/value relation. Is there a way make it work?

Delete the translations by default

In my opinion, since a translation record is useless without a Translatable model related to it, it should be deleted by default by the package using some kind of technique like an event listener on the delete event.

Right now this logic is provided by Database engine on delete cascade feature or equivalent, so it will not work by default with Laravel's soft deletes.

This automatic deletion feature could also be turn off by adding a property to the package configuration file or in a specific model.

Without this feature, the user have to override the delete method in the model like this

public function delete()
{
  $this->translations()->delete();
  $this->translations->each->delete(); // or like this if you have soft-deletes and want to keep the records
  return parent::delete();
}

This is a really huge breaking change, maybe the package could have this feature turned off by default for a few versions 🤔

Error on Fresh Installation

Laravel 6
Issue 1:
Class App\Author contains 18 abstract methods and must therefore be declared abstract or implement the remaining methods.

I have checked and this issue is occurring when I add "implements TranslatableContract" to the class

Issue 2: (Solved)
If I add
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
I am getting an error while migrating

SQLSTATE[HY000]: General error: 1005 Can't create table ts.post_translations (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table post_translations add constraint post_translations_post_id_foreign foreign key (post_id) references posts (id) on delete cascade)

Keep sort default when change locale

Hello all,

I have 3 languages: en, de, fr.

When I set app locale with de, the translations array will re-sort it to: de, en, fr. Now, I want to keep it as default: en,de,fr. How to do this? Please advise. Thank you so much.

Best Regards,

Chu

Save translatable value in pivot table

Can you please provide an example on how to save translatable value in pivot table. Have been working with this past three days. But still can't find a solution.

Transltable Slug Validation.

How to do slugs validation?

//categories
Schema::create('categories', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->integer('order')->index('order')->default(0);
          $table->tinyInteger('status')->default(1);
          $table->tinyInteger('show_menu')->default(1);
          $table->integer('parent')->index('parent')->nullable();
          $table->timestamps();
});

//categories translations schema
Schema::create('category_translations', function (Blueprint $table) {
          $table->bigIncrements('id');
          $table->string('locale')->index();
          $table->unsignedBigInteger('category_id');
          $table->string('name', 100)->index('name');
          $table->string('slug', 100)->unique('slug')->index('slug');
          $table->unique(['category_id', 'locale']);
          $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});

In my implementation we add content in single(en) language and users translate the content. Now with slugs, there is a possibility for some slugs to never get translated.

For example slug for category in English is entertainment and French slug is also entertainment and it can be both different for other categories.

Mutator - main model

Is is possible to run mutator on main model?

I have main model - Team

class Team extends Model implements TranslatableContract{
    use Translatable;

    public $translatedAttributes = [
        'name'
    ];`

and model fo translations: TeamTranslation

class TeamTranslation extends Model{
    public $timestamps = false;
    protected $fillable = [
        'name',
    ];

I would like to define mutator on main model (Team).

public function getNameAttribute($value){
    return $value.'__'.$this->another_property_from_team_model;
}

It seems that it does not work... What you suggest?

Searching in translation tables

I am creating search field.

Is there any simple way to search from translation tables.
Will the search be efficient than keeping data in same table if I have only two languages?

SQLSTATE[23000]: Integrity constraint violation or all foreign keys are zero.

If I use in my migrations (car_translations table):
$table->foreign('car_id')->references('id')->on('cars')->onDelete('cascade');
then I am getting this error:

SQLSTATE[23000]: Integrity constraint violation
, because some how the library can't get the id of the parent table (cars) inserted row, but there is an inserted row in the parent table (cars).
If I don't use that relation in cars_translations table:
$table->foreign('car_id')->references('id')->on('cars')->onDelete('cascade');
all car_id's are zero. in cars_translations table.

I am using your example from the home page, but what I am doing different is that, I need to set the id of the cars table manual:
` $data = [
'id' => 89,
'en' => ['name' => 'My first post'],
'fr' => ['name' => 'Mon premier post'],
];

    $post = Car::create($data);`

Polymorphic Relationships?

Does translatable handle polymorphic relationships? do you have a test or example that explains how to handle polymorphism?

Remove need to specify the language when updating Eloquent object

Let's say we have a product that has some translatable attributes for example name.
Would be nice if you could just do this.

$product = $product->update(request()->all());
or
$post->title = 'My cool post'; // uses default locale.
$post->save();

And it will update using default locale. Now you have to specify when updating:

current:
$post->translate('en')->title = 'My cool post';
$post->save();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.