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:

JavaScript

i´m traying this:

JavaScript

i have a relation between blog and blog_category with:

JavaScript

i want to do in my view appear for example:

JavaScript

in my view i´m doing this:

JavaScript

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

JavaScript

You can access the count in your foreach loop

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