Laravel when loading a relationship does not appear when returning as json

Asked

Viewed 58 times

0

When trying to load a product’s images are not included when returning

Model:

class Product extends Model
{
    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }
}

Controller:

class HomeController extends Controller
{
    public function getProducts()
    {
        $products = Product::with('images')->find(1);    
        return response()->json( $products, 200);
    }
}

Upshot:

{
  "id": 1,
  "name": "Tenis Adidas Flow Limited Edition",
  "price": 549.99,
  "stock": 0,
  "active": 0,
  "created_at": "17-06-20",
  "updated_at": "20-06-20"
}

If I make one $products->images in return works and stays like this:

[
  {
    "id": 5,
    "path": "products/1/SR84EetnuQW7WDetQBAurHypJPwrOiddyXWFDkAh.jpeg",
    "product_id": 1
  },
  {
    "id": 12,
    "path": "products/1/7cIkR4i0F3zY6fsKibqvKQIxtSEusCZmrmxx75nk.jpeg",
    "product_id": 1
  }
]

then I believe that the relationship is working properly, but I can not understand why not go in return.

1 answer

0

I managed to get around the situation by overwriting the model toArray

public function toArray()
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'price' => $this->price,
        'stock' => $this->stock,
        'active' => $this->active,
        'images' => $this->images->toArray(),
        'created_at' => $this->created_at->format('d-m-y'),
        'updated_at' => $this->updated_at->format('d-m-y'),
    ];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.