-
Notifications
You must be signed in to change notification settings - Fork 21
/
Category.php
47 lines (35 loc) · 1.12 KB
/
Category.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class Category extends Model
{
use HasFactory, SoftDeletes;
protected $guarded = ['id'];
public static function tree()
{
$allCategories = Category::get();
$rootCategories = $allCategories->whereNull('parent_id');
self::formatTree($rootCategories, $allCategories);
return $rootCategories;
}
private static function formatTree($categories, $allCategories)
{
foreach ($categories as $category) {
$category->children = $allCategories->where('parent_id', $category->id)->values();
if ($category->children->isNotEmpty()) {
self::formatTree($category->children, $allCategories);
}
}
}
public function images(): MorphMany
{
return $this->morphMany(Image::class, 'imageable');
}
public function isChild(): bool
{
return $this->parent_id !== null;
}
}