|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Backpack\MenuCRUD\app\Models; |
|
4
|
|
|
|
|
5
|
|
|
use Backpack\CRUD\app\Models\Traits\CrudTrait; |
|
6
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
7
|
|
|
|
|
8
|
|
|
class MenuItem extends Model |
|
9
|
|
|
{ |
|
10
|
|
|
use CrudTrait; |
|
11
|
|
|
|
|
12
|
|
|
protected $table = 'menu_items'; |
|
13
|
|
|
protected $fillable = ['name', 'type', 'link', 'page_id', 'parent_id']; |
|
14
|
|
|
|
|
15
|
|
|
public function parent() |
|
16
|
|
|
{ |
|
17
|
|
|
return $this->belongsTo('Backpack\MenuCRUD\app\Models\MenuItem', 'parent_id'); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function children() |
|
21
|
|
|
{ |
|
22
|
|
|
return $this->hasMany('Backpack\MenuCRUD\app\Models\MenuItem', 'parent_id'); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function page() |
|
26
|
|
|
{ |
|
27
|
|
|
return $this->belongsTo('Backpack\PageManager\app\Models\Page', 'page_id'); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Get all menu items, in a hierarchical collection. |
|
32
|
|
|
* Only supports 2 levels of indentation. |
|
33
|
|
|
*/ |
|
34
|
|
|
public static function getTree() |
|
|
|
|
|
|
35
|
|
|
{ |
|
36
|
|
|
$menu = self::orderBy('lft')->get(); |
|
37
|
|
|
|
|
38
|
|
|
if ($menu->count()) { |
|
39
|
|
|
foreach ($menu as $k => $menu_item) { |
|
40
|
|
|
$menu_item->children = collect([]); |
|
41
|
|
|
|
|
42
|
|
|
foreach ($menu as $i => $menu_subitem) { |
|
43
|
|
|
if ($menu_subitem->parent_id == $menu_item->id) { |
|
44
|
|
|
$menu_item->children->push($menu_subitem); |
|
45
|
|
|
|
|
46
|
|
|
// remove the subitem for the first level |
|
47
|
|
|
$menu = $menu->reject(function ($item) use ($menu_subitem) { |
|
48
|
|
|
return $item->id == $menu_subitem->id; |
|
49
|
|
|
}); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return $menu; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function url() |
|
|
|
|
|
|
59
|
|
|
{ |
|
60
|
|
|
switch ($this->type) { |
|
|
|
|
|
|
61
|
|
|
case 'external_link': |
|
62
|
|
|
return $this->link; |
|
|
|
|
|
|
63
|
|
|
break; |
|
|
|
|
|
|
64
|
|
|
|
|
65
|
|
|
case 'internal_link': |
|
66
|
|
|
return is_null($this->link) ? '#' : url($this->link); |
|
|
|
|
|
|
67
|
|
|
break; |
|
|
|
|
|
|
68
|
|
|
|
|
69
|
|
|
default: //page_link |
|
70
|
|
|
if ($this->page) { |
|
|
|
|
|
|
71
|
|
|
return url($this->page->slug); |
|
|
|
|
|
|
72
|
|
|
} |
|
73
|
|
|
break; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@returnannotation as described here.