Post.php
TLDR
This file defines the Post
model class for the Blog system in the application. It extends the Model
class provided by Laravel and utilizes traits to include additional functionality. The Post
model represents a blog post and contains relationships with other models such as Author
, Category
, and Comment
.
Classes
Post
The Post
class is a model representing a blog post. It extends the Model
class provided by Laravel and includes the HasFactory
and HasTags
traits. It has the following attributes and methods:
- Attributes:
-
$table
: Specifies the database table to be used for storing blog posts. -
$casts
: Specifies the attribute types that should be cast to native.
-
- Methods:
-
author()
: Returns the relationship between a blog post and its author. It defines abelongsTo
relationship with theAuthor
model. -
category()
: Returns the relationship between a blog post and its category. It defines abelongsTo
relationship with theCategory
model. -
comments()
: Returns the relationship between a blog post and its comments. It defines amorphMany
relationship with theComment
model.
-
<?php
namespace App\Models\Blog;
use App\Models\Comment;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Spatie\Tags\HasTags;
class Post extends Model
{
use HasFactory;
use HasTags;
/**
* @var string
*/
protected $table = 'blog_posts';
/**
* @var array<string, string>
*/
protected $casts = [
'published_at' => 'date',
];
public function author(): BelongsTo
{
return $this->belongsTo(Author::class, 'blog_author_id');
}
public function category(): BelongsTo
{
return $this->belongsTo(Category::class, 'blog_category_id');
}
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}