Find the value in where in json clause

Viewed 47

I have coupons table where I have rules column which is json

rules:"{\"books\":[1,2,3,4,5]}"

and I have book table which has no relation with coupons table

I also CartVue.vue file where I have store the books in cart . Now I want to have a attribute called getCouponArrtibute() which will return the coupon where $coupon->rules->books has the particular book id from cart .

So far I have done this

public function getCouponAttribute()
{
    $discount = Coupon::whereJsonContains('rules->books', $this->id)->get();
    return $discount;
}

and From Cartvue.vue I can now access coupon property but it is returning null or empty array every time wheather that book id is in coupon->rules->books or not

1 Answers

Right now Eloquent believes that $discount->rules is a string. You need to cast this to an object, this is done by utilizing Eloquent Model $casts property. This is done by adding casts property on your Courpon.php model.

class Coupon {
    protected $casts = [
        'rules' => 'object',
    ];
}

This should make the access $coupon->rules->books work.

Related