Skip to main content

Overview

The BlogCategory model represents a category for blog posts in LaraCMS. Categories help organize posts into logical groupings, and posts can belong to multiple categories through a many-to-many relationship. Namespace: App\Models\BlogCategory File: app/Models/BlogCategory.php:7

Properties

Fillable attributes

name
string
required
The name of the category (e.g., “Technology”, “Tutorials”, “News”)

Relationships

posts()

Many-to-many relationship with the Post model. Returns: BelongsToMany<Post> Pivot table: blog_category_post
// Get all posts in a category
$category = BlogCategory::find(1);
$posts = $category->posts;

// Get categories with post count
$categories = BlogCategory::withCount('posts')->get();

Usage examples

Creating a category

$category = BlogCategory::create([
    'name' => 'Laravel Development'
]);

Assigning categories to a post

$post = Post::find(1);
$post->blogCategories()->attach([1, 2, 3]);

// Or sync categories (replaces existing)
$post->blogCategories()->sync([1, 2]);

Querying posts by category

// Get all posts in a specific category
$categoryPosts = BlogCategory::find(1)->posts()->paginate(10);

// Get posts that have any of multiple categories
$posts = Post::whereHas('blogCategories', function($query) {
    $query->whereIn('blog_categories.id', [1, 2, 3]);
})->get();

Database schema

The blog_categories table contains:
  • id - Primary key
  • name - Category name (string)
  • created_at - Timestamp
  • updated_at - Timestamp
The pivot table blog_category_post contains:
  • blog_category_id - Foreign key to blog_categories
  • post_id - Foreign key to posts

Post model

View Post model documentation

Blog feature

Learn about the blog feature

Build docs developers (and LLMs) love