🔴 Laravel Intermediate

What is View Composers in Laravel?

Answer

View Composers are callbacks or class methods that are called when a specific view is rendered. They allow you to automatically bind data to views every time they are rendered, without the controller needing to explicitly pass the data. Register in a service provider: View::composer("partials.sidebar", function($view) { $view->with("categories", Category::all()); }). Class-based: View::composer("partials.sidebar", SidebarComposer::class) — the composer class has a compose(View $view) method. Register for all views: View::composer("*", ...). Use cases: navigation menus that need the current user's permissions, sidebars with dynamic content, breadcrumbs, and any data shared across many views. View Composers are cleaner than controller constructor code for data that is needed across many unrelated views.