0

I have two models called category and sub-category

Category.php

class Category extends Model
{
    protected $table = 'category';

    public $timestamps = false;

    public function subCategory(){

        return $this->hasMany('App\Subcategory', 'category_id');
    }
}

Subcategory.php

class Subcategory extends Model
{
    protected $table = 'subcategory';

    public $timestamps = false;

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

and I have foreign key column called category_id in my subcategory table in database

this is how I am trying to get all the subcategories for the selected category in my controller

$subcategory = Category::all();

and my blade view

 <ul>
            @foreach($categories as $categories)
            <li class='has-sub'><a href='#'>{{ $categories->category_name }}</a>
                <ul>
                    @foreach($subcategory->subCategory() as $sub)
                        <li><a href='#'>{{ $sub->subcategory_name }}</a></li>
                    @endforeach
                </ul>
            </li>
            @endforeach

        </ul>

I am able to get all the categories name for now but I can't get the name of sub-categories for the category..What I am missing here?

4
  • 1
    categories as $categories change that to categories as $category Commented Sep 2, 2015 at 8:36
  • @aldrin27 I am getting parent category successfully, I am only having issue to get sub-categories for that category Commented Sep 2, 2015 at 8:41
  • Can you print_r($categories)? Commented Sep 2, 2015 at 8:43
  • I get name of id and name of category on doing print_r Commented Sep 2, 2015 at 8:51

1 Answer 1

1

Your models are fine, i would modify the controller and view to the following:

In your controller

 $categories = Category::with('subCategory')->get();

Now in this this case, your categories will be eager loaded with your subcategories. In your example, you make queries in a foreach loop, which is not efficient.

In your view

<ul>
    @foreach($categories as $category)
    <li class='has-sub'><a href='#'>{{ $category->category_name }}</a>
        <ul>
        @foreach($category->subCategory as $sub)
            <li><a href='#'>{{ $sub->subcategory_name }}</a></li>
        @endforeach
        </ul>
    </li>
    @endforeach
</ul>

Notice the variable names, as @aldrin27 mentioned in the comment! ($categories -> $category)

More tweaks

You could use one model for categories and subcategories:

function subCategory() {
    return $this->hasMany('App\Category', 'category_id');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.