KishorKurian's avatar

HasMany() only brings relations for first record

I have searched a lot for this, and I see a lot of questions saying the same, but I still cant figure out whats the issue or how to fix it.

I am trying to make a list of Categories and Subcategories to populate a select dropdown.

Categorymodel

public function subcategories()
{
     return $this->hasMany(self::class, 'parent_id','id');
}

Controller

public function categories(){
  //Pull categories
  $categories = Categories::with('subcategories')->whereNull('parent_id')->get();
  foreach($categories as $line)
  {
  echo $line->categoryname."\n";
    foreach($line->subcategories as $sub){
      echo $sub->categoryname."\n";
    }
  }
 
}

My table has NULL for parent id if the category is a parent.

The results I get the subcategories only for the first record. All other records shows 0 subcategories.

What am I doing wrong?

0 likes
1 reply
KishorKurian's avatar
KishorKurian
OP
Best Answer
Level 1

My bad. My code was right, but the seeder was entering wrong data into the database.

Solved.

Please or to participate in this conversation.