- schema for cart and product - define relationship, DTO, Resource and API collections - Add post and get endpoint for cart api
66 lines
1.5 KiB
PHP
66 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Product extends Model
|
|
{
|
|
protected $fillable = [
|
|
'title',
|
|
'slug',
|
|
'actual_price',
|
|
'list_price',
|
|
'description',
|
|
'product_category_id',
|
|
];
|
|
|
|
public function category(): BelongsTo
|
|
{
|
|
return $this->belongsTo(ProductCategory::class, 'product_category_id');
|
|
}
|
|
|
|
public function images(): HasMany
|
|
{
|
|
return $this->hasMany(ProductImage::class, 'product_id', 'id');
|
|
}
|
|
|
|
public function favoritedBy(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(User::class, 'favorite_products');
|
|
}
|
|
|
|
public function carts()
|
|
{
|
|
return $this->belongsToMany(Cart::class);
|
|
}
|
|
|
|
#[Scope]
|
|
protected function active(Builder $query): Builder
|
|
{
|
|
return $query->where('is_active', true);
|
|
}
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::saving(function ($product) {
|
|
if (empty($product->slug) || $product->isDirty('title')) {
|
|
$product->slug = Str::slug($product->title);
|
|
}
|
|
});
|
|
}
|
|
|
|
protected function casts()
|
|
{
|
|
return [
|
|
'is_active' => 'boolean',
|
|
];
|
|
}
|
|
}
|