Managing navigation menus can become challenging in Laravel applications as they grow, especially with dynamic elements like role-based access controls. This blog post explores how to simplify and structure your menus using a Menu Builder system, making them easier to maintain, extend, and scale.
The Problem
In many Laravel projects, Blade templates handle menu visibility using conditionals:
@can('viewAdmin') <a href="%7B%7B%20route('administration.index')%20%7D%7D"> {{ __('Administration') }} </a> @endcan
While this approach works for simple applications, it becomes cluttered and unmanageable as the number of menus increases.
The Solution
A Menu Builder system encapsulates menu logic into reusable classes, improving:
- Maintainability: Centralised menu definitions.
- Scalability: Dynamically generating menus based on roles or permissions.
- Reusability: Sharing menus across views.
Support my mission to empower the developer community by sponsoring my work—your contributions help me build and share valuable tools, insights, and resources: Learn more here.
Step-by-Step Implementation
1. Define a Gate for viewAdmin
To control access to the administration menu, define a viewAdmin gate in your AuthServiceProvider:
use Illuminate\Support\Facades\Gate; use App\Models\User; class AuthServiceProvider extends ServiceProvider { public function boot() { $this->registerPolicies(); Gate::define('viewAdmin', function (User $user) { return $user->hasRole('admin'); // Replace with your app's role-checking logic }); } }
2. Create the MenuItem Class
The MenuItem class defines all attributes of a menu item, such as label, URL, icon, and visibility:
<?php namespace App\Actions\Builder; use CleaniqueCoders\Traitify\Contracts\Builder; use InvalidArgumentException; class MenuItem implements Builder { private string $label; private string $url; private string $target = '_self'; private array $attributes = []; private array $children = []; private string $icon = 'o-squares-2x2'; private ?string $description = null; private ?string $tooltip = null; private $visible = true; private array $output = []; public function setLabel(string $label): self { $this->label = $label; return $this; } public function setUrl(string $url): self { $this->url = $url; return $this; } public function setTarget(string $target): self { $this->target = $target; return $this; } public function addAttribute(string $key, string $value): self { $this->attributes[$key] = $value; return $this; } public function addChild(MenuItem $child): self { $this->children[] = $child; return $this; } public function setIcon(string $icon): self { $this->icon = $icon; return $this; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function setTooltip(string $tooltip): self { $this->tooltip = $tooltip; return $this; } public function setVisible($visible): self { if (! is_bool($visible) && ! is_callable($visible)) { throw new InvalidArgumentException('The visible property must be a boolean or a callable.'); } $this->visible = $visible; return $this; } public function isVisible(): bool { return is_callable($this->visible) ? call_user_func($this->visible) : $this->visible; } public function build(): self { $this->output = [ 'label' => $this->label, 'url' => $this->url, 'target' => $this->target, 'attributes' => $this->attributes, 'icon' => $this->icon, 'description' => $this->description, 'tooltip' => $this->tooltip, 'children' => array_filter( array_map(fn (MenuItem $child) => $child->build()->toArray(), $this->children), fn (array $child) => ! empty($child) ), ]; return $this; } public function toArray(): array { return $this->output; } public function toJson(int $options = 0): string { return json_encode($this->toArray(), $options, 512); } }
3. Create the Menu Builder
The Menu builder resolves and constructs menus dynamically:
namespace App\Actions\Builder; class Menu { public static function make() { return new self; } public function build(string $builder) { $class = match ($builder) { 'navbar' => Navbar::class, 'sidebar' => Sidebar::class, 'administration' => Administration::class, default => Navbar::class, }; $builder = new $class; return $builder->build(); } }
Access the menus using a helper function:
<?php use App\Actions\Builder\Menu; if (! function_exists('menu')) { function menu(string $builder) { return Menu::make()->build($builder)->menus(); } }
4. Administration Menu
Define administration-specific menu items in the Administration class:
<?php namespace App\Actions\Builder\Menu; use App\Actions\Builder\MenuItem; use CleaniqueCoders\Traitify\Contracts\Builder; use CleaniqueCoders\Traitify\Contracts\Menu; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Gate; class Administration implements Builder, Menu { private Collection $menus; public function menus(): Collection { return $this->menus; } public function build(): self { $this->menus = collect([ (new MenuItem) ->setLabel(__('Issues')) ->setUrl(url(config('telescope.path'))) ->setTarget('_blank') ->setVisible(fn () => Gate::allows('viewTelescope')) ->setTooltip(__('View Telescope issues')) ->setDescription(__('Access application issues using Laravel Telescope')) ->setIcon('o-bug'), // Heroicon outline for a bug (new MenuItem) ->setLabel(__('Queues')) ->setUrl(url(config('horizon.path'))) ->setTarget('_blank') ->setVisible(fn () => Gate::allows('viewHorizon')) ->setTooltip(__('Manage queues')) ->setDescription(__('Access Laravel Horizon to monitor and manage queues')) ->setIcon('o-cog'), // Heroicon outline for settings/tasks (new MenuItem) ->setLabel(__('Access Control')) ->setUrl(route('security.access-control.index')) ->setVisible(fn () => Gate::allows('viewAccessControl')) ->setTooltip(__('Manage access control')) ->setDescription(__('Define and manage access control rules')) ->setIcon('o-lock-closed'), (new MenuItem) ->setLabel(__('Users')) ->setUrl(route('security.users.index')) ->setVisible(fn () => Gate::allows('viewUser')) ->setTooltip(__('Manage users')) ->setDescription(__('View and manage user accounts')) ->setIcon('o-user-group'), (new MenuItem) ->setLabel(__('Audit Trail')) ->setUrl(route('security.audit-trail.index')) ->setVisible(fn () => Gate::allows('viewAudit')) ->setTooltip(__('View audit trails')) ->setDescription(__('Audit logs for security and activity tracking')) ->setIcon('o-document-text'), ])->reject(fn (MenuItem $menu) => ! $menu->isVisible()) ->map(fn (MenuItem $menu) => $menu->build()->toArray()); return $this; } }
5. Define Routes
Add the following route configuration for the administration page:
<?php use Illuminate\Support\Facades\Route; Route::middleware(['auth:sanctum', 'verified', 'can:viewAdmin']) ->as('administration.') ->prefix('administration') ->group(function () { Route::view('/', 'administration.index')->name('index'); });
6. Usage in Blade Templates
Navigation Menu (navigation-menu.blade.php):
@can('viewAdmin') <a href="%7B%7B%20route('administration.index')%20%7D%7D"> <x-icon name="o-computer-desktop"></x-icon> {{ __('Administration') }} </a> @endcan
Administration Menu (administration/index.blade.php):
<x-app-layout> <x-slot name="header">{{ __('Administration') }}</x-slot> <div> <hr> <p><strong>Output</strong></p> <p>Here the final output that you can have:</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173418649412401.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Building Dynamic and Maintainable Menus in Laravel"></p> <blockquote> <p>Support my mission to empower the developer community by sponsoring my work—your contributions help me build and share valuable tools, insights, and resources: Learn more here.</p> </blockquote> <hr> <h3> <strong>Conclusion</strong> </h3> <p>This <strong>Menu Builder system</strong> simplifies navigation management in Laravel by:</p> <ol> <li>Centralising menu definitions for better maintainability.</li> <li>Dynamically controlling menu visibility using roles or permissions.</li> <li>Reusing menu logic across views and layouts.</li> </ol> <p>By adopting this approach, you can scale your navigation system seamlessly, even in complex applications. </p> <p>You may want to load your menu details from database and construct the menus that you want. But for me, this is good enough. I don't have projects require me to use database driven menu configuration.</p> <p>The codes can be found here. </p> <p>Try it out and share your thoughts! ?</p> <hr> <p>Photo by LinedPhoto on Unsplash</p> </div> </x-app-layout>
The above is the detailed content of Building Dynamic and Maintainable Menus in Laravel. For more information, please follow other related articles on the PHP Chinese website!

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
