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