Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ethar's avatar
Level 5

Laravel API Resource: Loading relationship

hi i have this data

[
    {
        "id": 2,
        "name": "Blaze Holcomb",
        "description": "Quae voluptatem pers",
        "price": 20,
        "img": "/images/products/newyork_careers.jpg",
        "otherimg": null,
        "coupon_id": 3,
        "coupon": {
            "id": 3,
            "copounname": "General Discount",
            "discount": 20
        }
    },
    {
        "id": 3,
        "name": "Kyla Strickland",
        "description": "Qui pariatur Archit",
        "price": 5,
        "img": "/images/products/bag_1.png",
        "otherimg": null,
        "coupon_id": null,
        "coupon": null
    },

i want to use API Resource i created this Api Resource

        return [
            'id' => $this->id,
            'name' => $this->name,
            'price'=> $this->price,
            'img'=> $this->img,
            'otherimg'=> $this->otherimg,
            'description'=> $this->description,
            'coupon'=> $this->coupon->copounname,
            'discount'=> $this->coupon->discount,
        ];

but i got this error

ErrorException: Trying to get property 'copounname' 

any help how load the relationship

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

There is no coupon whenever coupon_id is null - just mitigate for that case:

return [
    'id' => $this->id,
    'name' => $this->name,
    'price'=> $this->price,
    'img'=> $this->img,
    'otherimg'=> $this->otherimg,
    'description'=> $this->description,
    'coupon'=> $this->coupon->copounname ?? null,
    'discount'=> $this->coupon->discount ?? null,
];
1 like

Please or to participate in this conversation.