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

ethar's avatar
Level 5

return specific field from realtion when using api resource

i have (product, copoun) tables relation betwen 2 table is

class Products extends Model
{
    function Coupon(){
        return $this->belongsTo('App\Models\Coupons');
    }
}

when using API Resourdce to get products and copoun (if copoun_id ) have value, and copoun is active, i use this api resource

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'price'=> $this->price,
            'coupon' => $this->coupon(function ($item) {
                return [
                    'discount'=>$item->discount
                ];
            })->where('active',1)
                ->where('begin_date', '<=', Carbon::now())
                ->where('end_date', '>=', Carbon::now())
                ->first()
        ];
    }

and i get these values

{
"data": [
{
	"id": 1,
	"title": "تفاح",
	"price": 5,
	"coupon": {
		"id": 1,
		"vimg": "/images/copoun/apple.png",
		"coupon_ar": "Soluta corrupti aut",
		"coupon_en": null,
		"discount": 50,
		"active": 1,
		"begin_date": "2021-03-22 00:00:00",
		"end_date": "2021-08-12 00:00:00",
		"admin_id": 1,
		"created_at": "2021-07-12T12:46:24.000000Z",
		"updated_at": "2021-07-12T21:53:21.000000Z",
		"deleted_at": null
	}
},
{
	"id": 2,
	"title": "بطيخ صيفي ع السكين",
	"price": 10,
	"coupon": null
}
]
}

my question how can i get ust discount from copoun , i dont need all values as (id, vimg,coupon_ar,coupon_en,active,begin_date.....)

0 likes
6 replies
tykus's avatar

What is this:

$this->coupon(function ($item) {
                return [
                    'discount'=>$item->discount
                ];
            })->where('active',1)
                ->where('begin_date', '<=', Carbon::now())
                ->where('end_date', '>=', Carbon::now())
                ->first()
1 like
ethar's avatar
Level 5

if coupon is active and begin_date <= now and end_date > now must return discount value, if not return null

tykus's avatar

I mean $this->coupon() as a function? Why are you doing this in the resource?

1 like
ethar's avatar
Level 5

@tykus cause this is the only way that success with me to return coupon based on conditions, i try to do it from eloquent but not success.

tykus's avatar

Is there something else (property/method) in the Product model named coupon?

1 like

Please or to participate in this conversation.