Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65840086/checking-for-the-presence-of-posts-in-a-category-does-not-work-php-blade-lara

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...