Search code examples
laraveleloquentforeign-keysmany-to-manyparent-child

Laravel 5.8 ManyToMany relationship child relation usign foreign key doesn't work


When I call my image resource it returns the correct data from my model:

Image resource:

     return [
         'id' => $this->id,
         'name' => $this->name,
         'presentation' => $this->presentation->description,
         'slug' =>$this->filename
    ];

Image Model:

    public function presentation()
    {
        return $this->hasOne(ProductPresentation::class, 'id', 'presentation_id');
    }

Returns:

{
    "data": [
        {
            "id": 1,
            "name": "White Gold",
            "presentation": "Product x",
            "slug": "products/white-gold.jpg"
        }
}

But when I call the manyToMany (Products -> images) relation I only get the the Id not the foreign relation

    "data": [
        {
            "id": 1,
            "name": "White Gold",
            "price": "€ 10,00",

            "images": [
                {
                    "id": 1,
                    "name": "White Gold",
                    "filename": "products/white-gold.jpg",
                    "presentation_id": 1
                }
            ]
        },

The Products resource calls the image resource but this doesn't load the relation ( need "presentation": "Product x" instead of "presentation_id": 1)

Using resource:

        return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->formattedPrice,
            'images' => $this->images
        ];

using model:

    public function images()
    {
        return $this->belongsToMany(Image::class);
    }

So the question would be how do I add the relation to belongsToMany(Image::class)


Solution

  • Try to change

    return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->formattedPrice,
            'images' => $this->images
        ];
    

    To

    return [
            'id' => $this->id,
            'name' => $this->name,
            'price' => $this->formattedPrice,
            'images' => YourImageResource::collection($this->images)
        ];