Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

php - How to create a database-driven multi-level navigation menu using Laravel

I'm new to Laravel 4 and I'm totally confused about it's models. I'm trying to create a database-driven navigation menu for my project and all I know is I have to create a model to interact with the database (based on my knowledge from codeigniter). I have been studying alot and I'm tired of not being able to go forward, this is the code I have come up with till now:

/app/models/navigation.php

<?php

class Navigation extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'navigation';

    /**
     * Get the unique identifier for the menu item.
     *
     * @return mixed
     */
    public function getItemIdentifier()
    {
        return $this->getKey();
    }

}

And this is my Navigation database table I will use for this Model:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So after doing much more searching and reading from different sources this is what I came up with and it's working fine:

/app/models/Navigation.php

<?php

class Navigation extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'navigation';

    public function parent() {

        return $this->hasOne('navigation', 'id', 'parent_id');

    }

    public function children() {

        return $this->hasMany('navigation', 'parent_id', 'id');

    }  

    public static function tree() {

        return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

    }

}

/app/controllers/HomeController.php

<?php

class HomeController extends BaseController {

    protected $layout = "layouts.main";

    public function showWelcome()
    {

        $items = Navigation::tree();

        $this->layout->content = View::make('layouts.home.index')->withItems($items);

    }

}

/app/views/layouts/home/index.blade.php

<ul>
    @foreach($items as $item)
        <li>{{ $item->title }}
            @foreach($item['children'] as $child)
            <li>{{ $child->title }}</li>
            @endforeach
        </li>
    @endforeach
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...