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

Tuesday, April 19, 2022

[FIXED] How do I achieve a count for regions in a sub menu of categories using Laravel?

 April 19, 2022     eager-loading, eloquent, laravel, parent-child, submenu     No comments   

Issue

I’m trying to get a count of listings in regions under a category.

The menu for regions on the home page shows a count of all listings in their regions from every category. On the categories page I’m trying to show a count for regions, that have listings in a selected category.

In my Listing Model

 public function scopeInCategory($query, Category $category)
 {
    return $query->whereIn('category_id', [$category->id]);
 }

 public function region()
 {
    return $this->belongsTo(Region::class);
 }

In my Region model

 public function listings()
 {
    return $this->hasMany(Listing::class);
 }

In my CategoryController

class CategoryController extends Controller
{

    public function index(Category $category)
    {

        $regions = Region::with(['listings' => function($query) use ($category) {
        
            $query->inCategory($category);
        }])->first('region')->get();

       return view('categories.index', compact('regions'));
   }
}

and in my region_dropdown.blade.php

 @foreach($regions as $region)
   
     <a class="dropdown-item" href="#">{{ $region->name }} 
    ( {{ $region->listings->count() }} )</a>
     
 @endforeach

But this is not working the region menu still shows a count of all listings in every category on the categories page.


Solution

You can use Eloquent's withCount method to get a count of Listings under each Region by a specific Category and then access the counted value on each Region by accessing the listings_count attribute that Eloquent will initialize for you.

class CategoryController extends Controller
{
    public function index(Category $category)
    {
       $regions = Region::withCount([
           'listings' => fn($q) => $q->where('category_id', $category->id)
       ])->get();
       return view('categories.index', compact('regions'));
   }
}

And in your blade file:

@foreach($regions as $region)
    <a class="dropdown-item" href="#">
        {{ sprintf('%s (%d)', $region->name, $region->listings_count) }}
    </a>
@endforeach

Feel free to ask for any clarification.



Answered By - ths
Answer Checked By - Pedro (PHPFixing Volunteer)
  • 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