Optimizing View Data with View Composers and View Creators
As applications grow, you’ll notice certain data always repeating across multiple pages. Examples include: header data, categories list, or sidebar statistics. If you pass these in every show() or index() method of your Controller, the codebase becomes bloated unnecessarily.
1. Limitations of View::share()
The simplest way to share data is passing View::share() in the AppServiceProvider.
View::share('categories', Category::all());
Disadvantage: This query runs on every request, even for AJAX requests returning JSON or pages that don't even include the header. Very resource-intensive!
2. Using View Composers with Closures
View Composers only execute data fetching when that view is about to be rendered.
use Illuminate\Support\Facades\View;
public function boot()
{
View::composer('layouts.sidebar', function ($view) {
$view->with('recentPosts', Post::latest()->take(5)->get());
});
}
Now, only when a request loads resources/views/layouts/sidebar.blade.php will the Post::latest() query trigger. You can even bind a Composer to multiple views using wildcards:
View::composer(['pages.*', 'posts.*'], function ($view) { ... });
3. View Composers via Classes (Great for large projects)
Instead of stacking Closures in AppServiceProvider, create a dedicated class: App\View\Composers\SidebarComposer.
namespace App\View\Composers;
use Illuminate\View\View;
use App\Models\Post;
class SidebarComposer
{
public function compose(View $view)
{
$view->with('recentPosts', Post::latest()->take(5)->get());
}
}
Register the class in the Provider:
use App\View\Composers\SidebarComposer;
use Illuminate\Support\Facades\View;
View::composer('layouts.sidebar', SidebarComposer::class);
4. View Creators - What's the Diff?
View Composers run right before the view is rendered. In contrast, View Creators run immediately after the View is instantiated (before child views render and before any override data from the controller is merged in).
View::creator('profile', ProfileCreator::class);
You would use Creators when you want the Controller to be able to override the default variables provided by the view creator. But practically, in 95% of use-cases, View Composers are what you need.
Summary
- Use View Composers for components like Navigations, Footers, Sidebars, and User Panels.
- Always be careful with N+1 Entity queries, and cache the data in the
compose()method to make your Blog incredibly fast!