Home > Blockchain >  Laravel Resource return value from another Resource?
Laravel Resource return value from another Resource?

Time:01-17

I tried to find a solution here but nothing worked. I want to return values from TagResource using MealResource because I have TagTranslations table and I'm getting the data from the table with translations in TagResource.

Relationships are correctly formed, meal and tag models are connected via meal_tags table and tagtranslations belongsTo Tag::class.

I used TagResource like this:

class TagResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $translation = $this->translations->where('tag_id', $this->id)->first();
            return 
            [
                'id' => $this->id,
                'title' => $translation->title,
                'slug' => $translation->slug,
            ];
    }
}

and MealResource like this:

public function toArray($request)
    {
        $translation = $this->translations->where('meal_id', $this->id)->first();
        $category_translation = $this->category->translations->where('category_id', $this->category->id)->first();


        return [
            'id' => $this->id,
            'title' => $translation->title,
            'decription' => $translation->description,
            'category' => [
                'id' => $this->category->id,
                'title' => $category_translation->title,
                'slug' => $category_translation->slug,
            ],
            'tags' => FILL IN THE BLANK (have used TagResource:collection() and new TagResource()) and didnt work


        ];
    }

CodePudding user response:

public function toArray($request)
    {
        $translation = $this->translations->where('meal_id', $this->id)->first();
        $category_translation = $this->category->translations->where('category_id', $this->category->id)->first();

        return [
            'id' => $this->id,
            'title' => $translation->title,
            'decription' => $translation->description,
            'category' => [
                'id' => $this->category->id,
                'title' => $category_translation->title,
                'slug' => $category_translation->slug,
            ],
            'tags' => TagResource::collection($this->tags),
        ];
    }

If all the Relationships namings/mappings are correct then this will work.And please make sure that model are perfectly mapped respectively.

  • Related