Manage navigational elements in Laravel apps

Packages

June 14th, 2022

Manage navigational elements in Laravel apps

Laravel Navigation is a package by Spatie to manage menus, breadcrumbs, and other navigational elements in Laravel apps.

While the Spatie Laravel Menu package is a Html menu generator for Laravel, think of this package as a "renderless component" for navigation components:

app(Navigation::class)
->add('Home', route('home'))
->add('Blog', route('blog.index'), function (Section $section) {
$section
->add('All posts', route('blog.index'))
->add('Topics', route('blog.topics.index'));
})
->addIf(Auth::user()->isAdmin(), function (Navigation $navigation) {
$navigation->add('Admin', route('admin.index'));
});
 
// Render to tree
app(Navigation::class)->tree();
 
/*
 
[
{ "title": "Home", "url": "/", "active": false, "children": [] },
{
"title": "Blog",
"url": "/blog",
"active": false,
"children": [
{ "title": "All posts", "url": "/blog", "active": false, "children": [] },
{ "title": "Topics", "url": "/blog/topics", "active": true, "children": [] }
],
},
{ "title": "Admin", "url": "/admin", "active": false, "children": [] }
]
 
*/

With this package you and also generate breadcrumbs from navigation using the following method:

// Append additional pages in your controller
app(Navigation::class)->activeSection()->add($topic->name, route('blog.topics.show', $topic));
 
// Render to breadcrumbs
app(Navigation::class)->breadcrumbs();
 
/*
[
{ "title": "Blog", "url": "/blog" },
{ "title": "Topics", "url": "/blog/topics" },
{ "title": "Laravel", "url": "/blog/topics/laravel" }
]
*/

You can learn about this package, get full installation instructions, and view the source code on GitHub. Thanks to Sebastian De Deyne and the Spatie team for this package, and all the fantastic open-source PHP and Laravel packages like this one 👏

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.