Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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


                                    <!--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

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading