What seems to be the problem:
I am trying to get the quantity of posts in each category.
Steps to Reproduce:
I have a livewire component, which displays side menu of categories. I have added a line
$this->postsCount = Post::where(‘category_id’, ‘=’, $id)->count();
to get the quantity of posts in each category.
Here is my component:
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
use App\Models\Category;
class Cats extends Component
{
public $categories, $postsCount;
public function mount(Category $id)
{
$this->categories = Category::all();
$this->postsCount = Post::where('category_id', '=', $id)->count();
}
public function render()
{
return view('livewire.cats');
}
}
Here is my view of the side menu
@foreach($categories as $category)
<ul class="list-group list-group-flush">
<li class="list-group-item">
<a href="{{ route('category', $category->id) }}" style="font-size:16px;color: black">
{{ $category->name }} {{ $category->postsCount }}
</a>
</li>
</ul>
@endforeach
So, I get just 0 near each category.
Relationships between posts and categories are the following:
public function category()
{
return $this->belongsTo(Category::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
Are you using the latest version of Livewire:
Yes
Guys, pls help🙏