Viewing File: /home/ubuntu/route-and-root-backend-base/app/Models/Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

use App\Helpers\Helper;

class Category extends Model
{
    use HasFactory;

    protected $hidden = ['id','unique_id'];

    protected $appends = ['category_id', 'category_unique_id', 'description_formatted'];

    protected $guarded = ['id', 'picture'];

    public function getCategoryIdAttribute() { 

        return $this->id;
    }

    public function getCategoryUniqueIdAttribute() {

        return $this->unique_id;
    }

    public function getDescriptionFormattedAttribute() {

        return strip_tags($this->description);
    }

    public function scopeApproved($query) {

        return $query->where('status', APPROVED);
    }

    public function subCategories() {

        return $this->hasMany(SubCategory::class);
    }

    public function products() {

        return $this->hasMany(Product::class);
    }

    public function availableProducts() {

        return $this->hasMany(Product::class)->where(['visible_status' => YES, 'status' => APPROVED]);
    }

    public static function boot() {

        parent::boot();

        static::creating(function ($model) {

            $model->attributes['unique_id'] = "C-".uniqid();

        });

        static::created(function($model) {

            $model->attributes['unique_id'] = routefreestring(strtolower($model->attributes['name']));

            $model->save();
        
        }); 

        static::updating(function ($model) {

            $model->attributes['unique_id'] = routefreestring(strtolower($model->attributes['name']));
            
        });

        static::deleting(function ($model) {

            foreach($model->subCategories as $subCategory) {

                $subCategory->delete();
            }

            Helper::storage_delete_file($model->picture, CATEGORY_FILE_PATH);
            
        });

    }
}
Back to Directory File Manager