Sid
Sid

Reputation: 5843

laravel hasMany relationship not working as expected

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?

Upvotes: 0

Views: 736

Answers (1)

Iamzozo
Iamzozo

Reputation: 2358

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');
}

Upvotes: 1

Related Questions