What is View Composers in Laravel?
Why Interviewers Ask This
This question targets practical, hands-on experience with Laravel. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
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.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Laravel answers easy to follow.