Home > other >  Could not find the relationship between tables
Could not find the relationship between tables

Time:08-26

Product Model

class Product extends Model{
        
            use HasFactory;
        
            protected $fillable = ['category_id', 'name', 'description', 'price'];
        
            public function  category(){
                     
                
                return $this->belongs('App\Models\Catogery');
            
            }
        }

Catogery Model

 class Catogery extends Model{
    use HasFactory;
    public function products()
        {
        return $this->hasMany('App\Models\Product');
        }
    }

ProductController

public function index()
{
   $products = Product::with('category')->get();
   return $products; 
}

I did write the above code to extract the all the products in each category.But It gives the following error.

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

CodePudding user response:

you have a typo in the Product model:

return $this->belongs('App\Models\Catogery');

it needs to be:

return $this->belongsTo('App\Models\Catogery');

and it will work.

  • Related