Skip to content
Advertisement

create counter for blog categories in laravel

I´m traying to create one counter for my blog´s categories. This should appear to the right name side of my category . i´m using my model with variable appends, that after i will use in my blade for show my result in one span. But i don´t know very well how i can use count in my Model. I´m doing this in my model Blog.

my variable appends contain:

protected $appends = [
        'custom_fields',
        'has_media',
        'restaurant',
        'blog_category',
        'viewer',
        'postCounter',
    ];

i´m traying this:

return $this->blogs()->count();

i have a relation between blog and blog_category with:

public function blogCategory()
    {
        return $this->belongsTo(AppModelsBlogCategory::class, 'blog_category_id', 'id');
    }

i want to do in my view appear for example:

innovation   (2)

in my view i´m doing this:

@foreach($categories as $category)
     <li><a href="{{ url('blogs/'.$category->name) }}">{{ trans('web.blog_category_'.$category->name) }}</a><span>{{$category->postCounter}}</span></li>
@endforeach

but always returned me 0, and i have post with categories

updated

enter image description here

Advertisement

Answer

With laravel relationship withCount you can do this easily. If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

add withCount method to your query

$categories = Category::withCount('blogCategory')->get();

You can access the count in your foreach loop

// $category->blogCategory_count
@foreach($categories as $category)
   <li>
      <a href="{{ url('blogs/'.$category->name) }}"> 
         {{trans('web.blog_category_'.$category->name) }}
      </a>
      <span>{{$category->blogCategory_count}}</span> 
   </li>
@endforeach

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement