spatie / laravel-translatable

Making Eloquent models translatable

Home Page:https://spatie.be/docs/laravel-translatable

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

provide a way to fetch records in a specific language only

adnane-ka opened this issue · comments

i'v integrated the package with an application that i'm working on, and multi-language fields are returned like:

{
   title: {
      en: "That's a title in english",
      ar: "That's a title in arabic."
   }
}

and that's okey.

but, what i really want is something like:

{
   title: "That's a title in english"
}

with specifying the target wanted language "en" as a dynamic thing like a query param or something sent in Headers. so if switched to "ar" for example the response would look like:

{
   title: "That's a title in arabic"
}

i didn't like the way i achieved that using loops and so much code. is there any short-handed way to do that with that package?

Consider using mutators for automatically retrieving models with strings already localized.
Check this similar issue: #320 (comment)

Consider using mutators for automatically retrieving models with strings already localized. Check this similar issue: #320 (comment)

Thanks for the inspiration @anibalealvarezs. i did that using mutators.
it did not seem to me logical to change the whole application locale to a target language just to fetch records in that language. so i did a couple of changes to that considering fetching from an API.

public function getTitleAttribute($value)
    {
        # fetch target language from request 
        $locale = request()->has('locale') ? request()->get('locale') : 'en';
        
        # make sure that target language is available 
        $locale = in_array($locale ,['en' ,'ar']) ? $locale : 'en';

        return json_decode($value)->{$locale};
    }

now i can send a GET request to /api/articles?locale=en to see results in english !

and everything is working really perfect!

Thanks!