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

meeadhassan's avatar

morphToMany and morphedByMany

I have three tables Products ,Categories and SubCategories and I want to use morphToMany relation with coupons ex :

products : id name

Categories : id name

subCategories : id name

coupon id name

specification_coupon : id coupon_id specified_id specified_type

class Coupon extends Model {

public function ProductsCoupon()
{
    return $this->morphedByMany('App\Product', 'specified','specification_coupons');
}


public function CategoryCoupon()
{
    return $this->morphedByMany('App\Category', 'specified','specification_coupons');
}


public function SubCategoryCoupon()
{
    return $this->morphedByMany('App\SubCategory', 'specified','specification_coupons');
} 

}

in category , product and subcategory Models I do like this class Category extends Model { public function SpecifiedTypes(){ return $this->morphToMany('App\Coupon', ' specified');

}

}

but the relation doesn't work when I do

dd($coupon->ProductsCoupon)

I got this

Collection {#2195 ▼ #items: [] }

please tell me what I did wrong , my project is on laravel 5.7

0 likes
3 replies
jdkdev's avatar

Hey @meeadhassan ,

Is your specified coupon table is supposed to be: specification_coupon OR specification_coupons

Best, Jordan

jdkdev's avatar

@meeadhassan

It's looks okay at first glance, do you have a way to dump the sql is creating out?

I've used Telescope to troubleshoot these types of things before and it will show you the query its building and you'll probably see why it's pulling zero. https://laravel.com/docs/5.8/telescope

Please or to participate in this conversation.