To develop a robust and maintainable Laravel application based on your specified database schema, we'll systematically create migrations and corresponding Eloquent models for each module. This approach ensures adherence to Laravel best practices, SOLID principles, and the DRY (Don't Repeat Yourself) principle. Each model will include comprehensive PHPDoc annotations to enhance code readability and maintainability.
The modules we'll cover are:
- Role Management Module
- User Management Module
- Category Management Module
- Tag Management Module
- Post Management Module
- Comment Management Module
- Analytics Management Module
Let's proceed module by module.
1. Role Management Module
Migration: Create Roles Table
We'll create the roles table with the specified fields and establish the necessary indexes, including a unique constraint on the slug field.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'roles' table.
*
* @return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps(); // Creates 'created_at' and 'updated_at'
$table->softDeletes(); // Creates 'deleted_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'roles' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
Model: Role
The Role model will define a many-to-many relationship with the User model through the role_user pivot table.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Role
*
* Represents a user role within the application.
*
* @package App\Models
*
* @property int $id
* @property string $name
* @property string $slug
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
*
* @property \Illuminate\Database\Eloquent\Collection|User[] $users
*/
class Role extends Model
{
use HasFactory, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'slug',
];
/**
* Users that belong to the role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
}
2. User Management Module
Migrations: Create Users and Role_User Tables
a. Create Users Table
We'll create the users table with the specified fields, ensuring unique constraints where necessary.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'users' table.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('avatar')->nullable();
$table->text('bio')->nullable();
$table->timestamps(); // 'created_at' and 'updated_at'
$table->softDeletes(); // 'deleted_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'users' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
b. Create Role_User Pivot Table
The role_user pivot table facilitates the many-to-many relationship between users and roles.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRoleUserTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'role_user' pivot table.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->constrained('roles')->onDelete('cascade');
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->primary(['role_id', 'user_id']);
$table->timestamps(); // Optional: To track when roles are assigned to users
});
}
/**
* Reverse the migrations.
*
* Drops the 'role_user' pivot table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
Model: User
The User model will define relationships with roles, posts, and comments. We'll utilize the HasRoles trait to manage role assignments conveniently.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
/**
* Class User
*
* Represents a user within the application.
*
* @package App\Models
*
* @property int $id
* @property string $name
* @property string $email
* @property string $password
* @property string|null $avatar
* @property string|null $bio
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
*
* @property \Illuminate\Database\Eloquent\Collection|Role[] $roles
* @property \Illuminate\Database\Eloquent\Collection|Post[] $posts
* @property \Illuminate\Database\Eloquent\Collection|Comment[] $comments
*/
class User extends Authenticatable
{
use HasFactory, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'avatar',
'bio',
];
/**
* The attributes that should be hidden for arrays and JSON.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Roles that belong to the user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Role::class)->withTimestamps();
}
/**
* Posts authored by the user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function posts()
{
return $this->hasMany(Post::class);
}
/**
* Comments made by the user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
3. Category Management Module
Migration: Create Categories Table
We'll create the categories table with the necessary fields and a unique constraint on the slug.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'categories' table.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->timestamps(); // 'created_at' and 'updated_at'
$table->softDeletes(); // 'deleted_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'categories' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Model: Category
The Category model defines a one-to-many relationship with the Post model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Category
*
* Represents a category for organizing posts.
*
* @package App\Models
*
* @property int $id
* @property string $name
* @property string $slug
* @property string|null $description
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
*
* @property \Illuminate\Database\Eloquent\Collection|Post[] $posts
*/
class Category extends Model
{
use HasFactory, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'slug',
'description',
];
/**
* Posts that belong to the category.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function posts()
{
return $this->hasMany(Post::class);
}
}
4. Tag Management Module
Migrations: Create Tags and Post_Tag Tables
a. Create Tags Table
We'll create the tags table with necessary fields and a unique constraint on the slug.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'tags' table.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps(); // 'created_at' and 'updated_at'
$table->softDeletes(); // 'deleted_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'tags' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
b. Create Post_Tag Pivot Table
The post_tag pivot table facilitates the many-to-many relationship between posts and tags.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'post_tag' pivot table.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');
$table->foreignId('tag_id')->constrained('tags')->onDelete('cascade');
$table->primary(['post_id', 'tag_id']);
$table->timestamps(); // Optional: To track when tags are attached to posts
});
}
/**
* Reverse the migrations.
*
* Drops the 'post_tag' pivot table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('post_tag');
}
}
Model: Tag
The Tag model defines a many-to-many relationship with the Post model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Tag
*
* Represents a tag for categorizing posts.
*
* @package App\Models
*
* @property int $id
* @property string $name
* @property string $slug
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
*
* @property \Illuminate\Database\Eloquent\Collection|Post[] $posts
*/
class Tag extends Model
{
use HasFactory, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'slug',
];
/**
* Posts that are tagged with the tag.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function posts()
{
return $this->belongsToMany(Post::class)->withTimestamps();
}
}
5. Post Management Module
Migrations: Create Posts Table
We'll create the posts table with the specified fields, ensuring proper foreign key constraints and indexing.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'posts' table.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
// Foreign keys
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->foreignId('category_id')->constrained('categories')->onDelete('cascade');
// Post details
$table->string('title');
$table->string('slug')->unique();
$table->text('content');
$table->text('excerpt')->nullable();
$table->string('featured_image')->nullable();
$table->enum('status', ['draft', 'published', 'archived'])->default('draft');
$table->timestamp('published_at')->nullable();
$table->string('seo_title')->nullable();
$table->text('seo_description')->nullable();
$table->timestamps(); // 'created_at' and 'updated_at'
$table->softDeletes(); // 'deleted_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'posts' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Model: Post
The Post model defines relationships with User, Category, Comment, Like, and Tag models. It also includes scopes for querying published posts.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Post
*
* Represents a blog post within the application.
*
* @package App\Models
*
* @property int $id
* @property int $user_id
* @property int $category_id
* @property string $title
* @property string $slug
* @property string $content
* @property string|null $excerpt
* @property string|null $featured_image
* @property string $status
* @property \Illuminate\Support\Carbon|null $published_at
* @property string|null $seo_title
* @property string|null $seo_description
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
*
* @property User $user
* @property Category $category
* @property \Illuminate\Database\Eloquent\Collection|Comment[] $comments
* @property \Illuminate\Database\Eloquent\Collection|Like[] $likes
* @property \Illuminate\Database\Eloquent\Collection|Tag[] $tags
*/
class Post extends Model
{
use HasFactory, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'user_id',
'category_id',
'title',
'slug',
'content',
'excerpt',
'featured_image',
'status',
'published_at',
'seo_title',
'seo_description',
];
/**
* The attributes that should be cast to native types.
*
* @var array<string, string>
*/
protected $casts = [
'published_at' => 'datetime',
];
/**
* User who authored the post.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Category to which the post belongs.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo(Category::class);
}
/**
* Comments associated with the post.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
/**
* Likes associated with the post.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function likes()
{
return $this->hasMany(Like::class);
}
/**
* Tags associated with the post.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
/**
* Scope a query to only include published posts.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublished($query)
{
return $query->where('status', 'published')->whereNotNull('published_at');
}
}
6. Comment Management Module
Migration: Create Comments Table
We'll create the comments table with self-referencing foreign keys for nested comments.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'comments' table.
*
* @return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
// Foreign keys
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');
$table->foreignId('parent_id')->nullable()->constrained('comments')->onDelete('cascade');
// Comment details
$table->text('content');
$table->enum('status', ['pending', 'approved', 'rejected'])->default('pending');
$table->timestamps(); // 'created_at' and 'updated_at'
$table->softDeletes(); // 'deleted_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'comments' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
Model: Comment
The Comment model defines self-referencing relationships for nested comments and associations with User and Post.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Comment
*
* Represents a comment on a post.
*
* @package App\Models
*
* @property int $id
* @property int $user_id
* @property int $post_id
* @property int|null $parent_id
* @property string $content
* @property string $status
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property \Illuminate\Support\Carbon|null $deleted_at
*
* @property User $user
* @property Post $post
* @property Comment|null $parent
* @property \Illuminate\Database\Eloquent\Collection|Comment[] $children
*/
class Comment extends Model
{
use HasFactory, SoftDeletes;
/**
* The possible statuses for a comment.
*/
public const STATUS_PENDING = 'pending';
public const STATUS_APPROVED = 'approved';
public const STATUS_REJECTED = 'rejected';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'user_id',
'post_id',
'parent_id',
'content',
'status',
];
/**
* User who authored the comment.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Post to which the comment belongs.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function post()
{
return $this->belongsTo(Post::class);
}
/**
* Parent comment in case of a nested comment.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function parent()
{
return $this->belongsTo(Comment::class, 'parent_id');
}
/**
* Child comments nested under this comment.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
7. Analytics Management Module
Migration: Create Analytics Table
We'll create the analytics table to track views, likes, and comments counts for each post.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAnalyticsTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'analytics' table.
*
* @return void
*/
public function up()
{
Schema::create('analytics', function (Blueprint $table) {
$table->bigIncrements('id');
// Foreign key
$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');
// Analytics data
$table->unsignedInteger('views_count')->default(0);
$table->unsignedInteger('likes_count')->default(0);
$table->unsignedInteger('comments_count')->default(0);
$table->timestamps(); // 'created_at' and 'updated_at'
});
}
/**
* Reverse the migrations.
*
* Drops the 'analytics' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('analytics');
}
}
Model: Analytics
The Analytics model defines a relationship with the Post model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Analytics
*
* Represents analytics data associated with a post.
*
* @package App\Models
*
* @property int $id
* @property int $post_id
* @property int $views_count
* @property int $likes_count
* @property int $comments_count
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
*
* @property Post $post
*/
class Analytics extends Model
{
use HasFactory;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'analytics';
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'post_id',
'views_count',
'likes_count',
'comments_count',
];
/**
* Post to which the analytics data belongs.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
Additional Considerations
Like Management Module (Assumed)
Since the Post model mentions a relationship with Like, it's assumed that a likes table and corresponding Like model exist. Below is an example implementation.
Migration: Create Likes Table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLikesTable extends Migration
{
/**
* Run the migrations.
*
* Creates the 'likes' table.
*
* @return void
*/
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
// Foreign keys
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->foreignId('post_id')->constrained('posts')->onDelete('cascade');
$table->timestamps(); // 'created_at' and 'updated_at'
// To prevent duplicate likes by the same user on the same post
$table->unique(['user_id', 'post_id']);
});
}
/**
* Reverse the migrations.
*
* Drops the 'likes' table.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('likes');
}
}
Model: Like
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Like
*
* Represents a 'like' on a post by a user.
*
* @package App\Models
*
* @property int $id
* @property int $user_id
* @property int $post_id
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
*
* @property User $user
* @property Post $post
*/
class Like extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'user_id',
'post_id',
];
/**
* User who liked the post.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Post that was liked.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function post()
{
return $this->belongsTo(Post::class);
}
}
Conclusion
By following this structured approach, we've created a comprehensive set of migrations and models that adhere to Laravel's best practices and the specified requirements. Each model is equipped with appropriate relationships, and migrations ensure data integrity through foreign keys and constraints. Additionally, PHPDoc annotations enhance code clarity, making the application easier to maintain and extend in the future.
Ensure to run migrations in the correct order to respect foreign key dependencies, typically by naming migration files with timestamps reflecting the creation sequence.
To execute all migrations, use the Artisan command:
php artisan migrate
This setup provides a solid foundation for building out the application's functionality, ensuring scalability, maintainability, and a seamless developer experience.