Astrotomic / laravel-translatable

A Laravel package for multilingual models
https://docs.astrotomic.info/laravel-translatable/
MIT License
1.22k stars 152 forks source link

does not save model translations #389

Closed jltrevizon closed 3 months ago

jltrevizon commented 4 months ago

Describe the bug Doesn´t save model translations.

To Reproduce Config Translatable: imagen

Create ModelTranslation imagen

Configure Model with Translatable ; imagen

populate translation table: imagen

Screenshots Testing using tinker imagen

Versions (please complete the following information)

jltrevizon commented 4 months ago

I have found the problem, it is in the protected property $with = [“translation”]; in ModelTranslation. I was using it this way to avoid loading unnecessary translations. Now my problem is, how can I return in the API response only the translation that the user requests in the request without having to show all the translation relationships?

Eyad-Bereh commented 4 months ago

Now my problem is, how can I return in the API response only the translation that the user requests in the request without having to show all the translation relationships?

You can hide the translations attribute either by using the $hidden attribute inside your Access model, for example:

protected $hidden = ["translations"];

Or maybe you can use the without() method on your model to prevent the translations relationship from loading:

Accessory::without("translations")->first();

But in my opinion, the best option would be to use an API Resource since you can get better control over the response form. There, you can choose to not send translations inside the response.

Of course, you can use a middleware to read the user locale and set it inside the application using a global middleware. Here's an example implementation that read the value of the Accept-Language header and adjusts the locale of the application:

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->hasHeader('Accept-Language') && !empty($request->header('Accept-Language'))) {
            $locale = $request->header('Accept-Language');
            $language = Locale::acceptFromHttp($locale);
            App::setLocale($language);
        }
        return $next($request);
    }
}
github-actions[bot] commented 3 months ago

This issue is stale because it has been open 21 days with no activity. Remove stale label or comment or this will be closed in 7 days