Product.php
TLDR
This file defines the Product
model for the Shop section of the application. It extends the Model
class and implements the HasMedia
interface for handling media files. The model has relationships with the Brand
, Category
, and Comment
models.
Classes
Product
The Product
class represents a product in the Shop section of the application. It extends the Model
class and implements the HasMedia
interface. The class contains the following methods and properties:
-
$table
: Specifies the table to use for storing product records. -
$casts
: Defines the data types of certain attributes, includingfeatured
,is_visible
,backorder
,requires_shipping
, andpublished_at
. -
brand()
: Returns the relationship between a product and its brand. It belongs to theBrand
model. -
categories()
: Returns the relationship between a product and its categories. It belongs to manyCategory
models through theshop_category_product
pivot table. -
comments()
: Returns the relationship between a product and its comments. It has manyComment
models through polymorphism.
<?php
namespace App\Models\Shop;
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\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Product extends Model implements HasMedia
{
use HasFactory;
use InteractsWithMedia;
/**
* @var string
*/
protected $table = 'shop_products';
/**
* @var array<string, string>
*/
protected $casts = [
'featured' => 'boolean',
'is_visible' => 'boolean',
'backorder' => 'boolean',
'requires_shipping' => 'boolean',
'published_at' => 'date',
];
public function brand(): BelongsTo
{
return $this->belongsTo(Brand::class, 'shop_brand_id');
}
public function categories(): BelongsToMany
{
return $this->belongsToMany(Category::class, 'shop_category_product', 'shop_product_id', 'shop_category_id')->withTimestamps();
}
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}