Home > Back-end >  How to get subcategory status and category status on Blade view?
How to get subcategory status and category status on Blade view?

Time:12-29

$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 >
                                    @foreach ($item->subcategory as $items)
                                   
                                    <li>
                                        <a href="#">{{ $items->subcategory_np }}</a>
                                    </li>
                                  
                                    @endforeach


                                    <!--Pages end-->
                                </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

CodePudding user response:

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.

  • Related