John Davidson

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

0 comments
Message:


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.



My Answer:
>posts->count()) > 0)
{{ $category->name }}
@else
{{ $category->name }}
@endif

However, this code does not work as expected. It does not prevent the user from clicking on the category even if there are no posts in that category.

One way to achieve this functionality is to check for the presence of posts in the controller before passing the categories to the view. You can modify the controller code to only pass categories that have posts associated with them.

Here is an example of how you can do this in your controller:

php
$categories = Category::withCount('posts')->get()->filter(function($category) {
return $category->posts_count > 0;
});

return view('categories.index', compact('categories'));


In this code, we are using the `withCount` method to count the number of posts associated with each category. We then filter out categories that have no posts associated with them. This way, only categories with posts will be passed to the view.

In your view, you can simply loop through the filtered categories and display them as links:

php
@foreach($categories as $category)
{{ $category->name }}
@endforeach


This way, the user will only see categories with posts and will not be able to click on categories that have no posts associated with them.

Rate this post

5 of 5 based on 1294 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us