PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

[FIXED] How to get subcategory status and category status on Blade view?

 December 29, 2021     eloquent, eloquent-relationship, laravel, laravel-8, php     No comments   

Issue

$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


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



Answered By - Jyotishmoy
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing