sohail49
1 month ago

Call to undefined relationship [category , subcategory] on model

Posted 1 month ago by sohail49

hi I am new to laravel and I get this error when defining a relationship

Call to undefined relationship [category , subcategory] on model [App\Models\Product].


// Product Model code

class Product extends Model
{
    use SoftDeletes;
    public $timestamp = true;
    public $fillable =  ['name','price','quantity','category_id','sub_category_id','description', 'image'];
    public $date= ['deleted_at'];

    public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }
    public function subCategory()
    {
        return $this->belongsTo('App\Models\subCategory');
    }


// category model code

class Category extends Model
{
    use SoftDeletes;
    public $timestamps = true;
    protected $fillable= ['id','name' , 'slug'];
    protected $date= ['deleted_at'];

    public function products()
    {
        return $this->hasMany(Product::class);
    }
    public function subCategories()
    {
        return $this->hasMany(SubCategory::class, 'parent_id');
    }


// subcategory mode code 


class SubCategory extends Model
{
    use SoftDeletes;
    public $timestamps = true;
    protected $fillable= ['id','name' , 'slug' ,'category_name','parent_id'];
    protected $date= ['deleted_at'];

    public function category()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

I have three tables in the database

products

categories

sub_categories

products table have column ( category_id ) and (sub_category_id) for the relation

and

sub-categories have column (parent_id) for the relation

Please sign in or create an account to participate in this conversation.