'boolean', 'is_active' => 'boolean', ]; /** * The attributes that are translatable. * * @var array */ protected $translatedAttributes = ['name']; /** * The attribute that will be slugged. * * @var string */ protected $slugAttribute = 'name'; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted() { static::addActiveGlobalScope(); } public static function findBySlug($slug) { return static::with('files')->where('slug', $slug)->firstOrNew([]); } public function isRoot() { return $this->exists && is_null($this->parent_id); } public function url() { return route('categories.products.index', ['category' => $this->slug]); } public static function tree() { return Cache::tags('categories') ->rememberForever(md5('categories.tree:' . locale()), function () { return static::with('files') ->orderByRaw('-position DESC') ->get() ->nest(); }); } public static function treeList() { return Cache::tags('categories')->rememberForever(md5('categories.tree_list:' . locale()), function () { return static::orderByRaw('-position DESC') ->get() ->nest() ->setIndent('¦–– ') ->listsFlattened('name'); }); } public static function searchable() { return Cache::tags('categories') ->rememberForever(md5('categories.searchable:' . locale()), function () { return static::where('is_searchable', true) ->get() ->map(function ($category) { return [ 'slug' => $category->slug, 'name' => $category->name, ]; }); }); } public function products() { return $this->belongsToMany(Product::class, 'product_categories'); } public function getLogoAttribute() { return $this->files->where('pivot.zone', 'logo')->first() ?: new File; } public function getBannerAttribute() { return $this->files->where('pivot.zone', 'banner')->first() ?: new File; } public function toArray() { $attributes = parent::toArray(); if ($this->relationLoaded('files')) { $attributes += [ 'logo' => [ 'id' => $this->logo->id, 'path' => $this->logo->path, 'exists' => $this->logo->exists, ], 'banner' => [ 'id' => $this->banner->id, 'path' => $this->banner->path, 'exists' => $this->banner->exists, ], ]; } return $attributes; } }