Get Appointment

Blog Single

Laravel fetch categories which has post counts

  • Vfix Technology
  • 17 Dec 2023
  • Laravel
  • 393 Views

To fetch only those categories in Laravel that have at least one post associated with them, you can use the following steps:

  1. Set up a one-to-many relationship between your categories and posts models. In the categories model, you can use the hasMany method to define the relationship. In the posts model, you can use the belongsTo method to define the inverse relationship.

  2. In your controller, you can use the withCount method on your categories query to count the number of posts associated with each category. This method will add a new column to your categories table with the count of posts.

  3. Use the having method on your categories query to filter the categories based on their post count. You can pass in a closure to the having method that specifies the condition for the post count.

  4. Use the get method on your categories query to retrieve the categories with their post count. You can pass in an array of columns to select if you only want to retrieve specific columns from the categories table.

Here's an example of how this could look in your controller:

$categories = Category::withCount('posts')
    ->having('posts_count', '>', 0)
    ->get(['id', 'name', 'posts_count']);

This will retrieve only those categories that have at least one post associated with them, with a count of the number of posts for each category. You can then pass the categories to your view to display them however you like.

I hope this helps! Let me know if you have any questions.

Tags
Share :


+91 8447 525 204 Request Estimate