Search code examples
phplaravelif-statementlaravel-bladelaravel-relations

Checking for the presence of posts in a category does not work. php, Blade, Laravel


I have a view with all categories, by clicking on a category, the user can go to that category. But I want to prevent going there if there are no posts in that category. I tried to do this:

@if(($category->id === $category->posts()) !== 0)
   <a class="btn btn-success" href="{{ route('category', $category->code)}}">Open</a>
@else
   <span class="btn btn-warning">No posts in this category</span>
@endif

posts() is an eloquent relationship in my Category model:

public function posts() {
   return $this->hasMany(Post::class);
}

But it doesn't work. All categories are written either "The post has no categories" or "Open". That is, the check does not work correctly.


Solution

  • in your blade file check condition like that

    @if($category->posts_count > 0)
       <a class="btn btn-success" href="{{ route('category', $category->code)}}">Open</a>
    @else
       <span class="btn btn-warning">No posts in this category</span>
    @endif
    

    in your controller used withCount method

    $category = Category::withCount('posts')->get();
    

    and in your category model add relationship if not added(one to many)

    public function posts(){
        return $this->hasMany(Post::class);
    }