Reputation: 13
I have the next stucture: table menus(id, title, type, parent_id, page_id) and pages(id, alias title,content) Model Menu
class Menu extends Model
{
public function parent()
{
return $this->belongsTo('App\Menu', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Menu', 'parent_id');
}
public function page()
{
return $this->belongsTo('App\Page', 'page_id');
}
}
I want get the next result:
-Item 1 (show name menu table)
-Item 2
-Subitem 1 and alias (show name **menu** table and show alias **page** table)
-Subitem 2 and alias
-Item 3
- Suitem 1 and alias
Eloquent query
$items = Menu::with(['children' => function($query){
$query->with('page');
}])->where(['parent_id' => null])->get();
view
@foreach($items as $item)
@if($item->children()->count() > 0)
@foreach($item->children as $child)
<li><a href="/page/">{{$child->title}}</a></li>
@endforeach
@else
<li><a href="/page/{{$item->page->alias}}">{{$item->title}}
@endforeach
How get alias page nested in foreach ?
Upvotes: 1
Views: 230
Reputation: 111889
You can use:
{{ $child->page->alias }}
to display child menu page alias assuming you have page
for each child.
Otherwise you can use:
{{ optional($child->page)->alias }}
if you are running Laravel 5.5 or:
{{ $child->page ? $child->page->alias : '' }}
if you are running Laravel < 5.5
Also you could improve eager loading and code a bit:
$items = Menu::with('children.page', 'page')->whereNull('parent_id')->get();
Upvotes: 2