jeudi 24 juin 2021

Model field mapping with eloquent in laravel using attribute

Hi I have a structure in db like this:

Category id name_pl name_en

Post id title body lang category

Ofcourse Post->category i related to Category->id. What I'm trying to achive is to get posts with category name depending on Post-lang like this:

{
   id: 1,
   title: "Something",
   body: "whatever",
   categoryName: "Category name in correct language"
}

. I've been trying to do that using atrribute in Post model like this:

    public function getCategoryNameAttribute()
    {
        $category = Category::find($this->category)->load('icon');
        return [
            'id' => $category->id,
            'name' => $this->lang === 'pl' ? $category->name_pl : $category->name_en,
        ];
    }

But in this case I have n+1 problem. I've been trying to use with() method but inside attribude method I get only category id. Any ideas?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire