Laravel - 无法输出父类别的痕迹

时间:2014-09-11 11:02:46

标签: laravel laravel-4 breadcrumbs

使用:https://github.com/davejamesmiller/laravel-breadcrumbs

我可以在视图中打印面包屑,没有任何问题:

Breadcrumbs::render('category', $category);

然后,如果我想打印父类别 - 我在breadcrumbs.php中执行:

Breadcrumbs::register('category', function($breadcrumbs, $category) {
    $breadcrumbs->parent('home');
    $breadcrumbs->push('»');

    foreach($category->parent as $parent) {
        $breadcrumbs->push($parent->title, '/category/' . $parent->slug);
    }

    $breadcrumbs->push($category->title, '/category/' . $category->slug);
});

我无法打印类别父级,这是我的类别模型:

public function parent() {
    return $this->hasOne('Category', 'id', 'parent_id');
}

但是,它输出一个空的<li></li>

如何在面包屑中打印类别父级?

2 个答案:

答案 0 :(得分:1)

由于每个类别只有一个父级(由hasOne关系定义),因此您可以替换这些代码:

...
foreach($category->parent as $parent) {
    $breadcrumbs->push($parent->title, '/category/' . $parent->slug);
}
...

这一行:

...
$breadcrumbs->push($category->parent->title, '/category/' . $category->parent->slug);
...

答案 1 :(得分:0)

或者你可以做一个递归函数,如:

Breadcrumbs::register('category', function($breadcrumbs, $category) {
    if ($category->parent)
        $breadcrumbs->parent('category', $category->parent);
    else
        $breadcrumbs->parent('blog');

    $breadcrumbs->push($category->title, route('category', $category->slug));
});