Search code examples
phplaraveleloquentlaravel-8eloquent-relationship

How to get subcategory status and category status on Blade view?


$categories = Category::with('subcategory')->where('status',1)->take(7)->get();

view()->share('categories', $categories);

model Category:

protected $fillable =[
    'category_en',
    'category_np',
    'status',
];

public function posts()
{
    return $this->hasMany(Post::class);
}

public function subcategory()
{
    return $this->hasMany(Subcategory::class); // category_id
}

Model Subcategory:

protected $fillable = [
    'subcategory_en',
    'status',
    'category_id',
    'subcategory_np',
];

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

My blade view:

@foreach ($categories as $item)
    <li>
        <a href="#">{{ $item->category_en }}</a>
                               
        @if ($item->subcategory->count() > 0)
            <ul class="nav-dropdown">
                @foreach ($item->subcategory as $items)
                <li>
                    <a href="#">{{ $items->subcategory_np }}</a>
                </li>                                      
                @endforeach
            </ul>
        @endif
    </li>
@endforeach

I got where category status 0 but don't get subcategory status 0.

I want to get both category and subcategory status 0 in blade view.

I am new in a laravel, please help.


Solution

  • You can add conditions to your relationship data by changing your query like this:

    $categories = Category::with(['subcategory' => function($query){
        $query->where('status', 1);
    }])->where('status',1)->take(7)->get();
    

    By doing this you are adding a where condition to your relationship data and it will only fetch all the subcategories with status 1.