Back to Blog
Lesson 43 of the Laravel Fundamentals: From Zero to Your First App course
LaravelJune 25, 20263 min read

Using View Composers in Laravel: A Guide to DRY Blade Templates

Learn how to use View Composers in Laravel to share data across your Blade templates without repeating code in your controllers. Keep your app DRY.

LaravelBladeView ComposersDRYPHPWeb Developmentbackend

Previously in this course, we explored Understanding Service Providers and the Laravel Service Container. In this lesson, we build on that foundation by using View Composers to share data across your application's UI, ensuring your code remains clean and maintainable.

The Problem: Controller Bloat

As your Task Manager app grows, you’ll likely need certain pieces of data to appear on every page. Perhaps you want to show a "Task Summary" in your sidebar, or display the current user's active project count in the header.

If you fetch this data in every single controller method, you'll quickly find yourself repeating the same database calls over and over again. This violates the DRY (Don't Repeat Yourself) principle and makes your controllers unnecessarily complex. While you could use Laravel view sharing: How to Use View::share() Correctly for truly global data, View Composers provide a more structured, performant, and organized way to handle this.

What are View Composers?

View Composers are callback functions or class methods that are called when a view is rendered. They allow you to "compose" a view with specific data just before it’s sent to the browser.

Think of them as a "middleware for your views." Instead of forcing a controller to know about every piece of data a layout file needs, the View Composer intercepts the rendering process and injects that data automatically.

Creating a View Composer

Let’s implement a composer to provide a list of "Priority Categories" to our sidebar, which is already set up using Implementing Blade Partials: A Guide to DRY Laravel Views.

First, create a directory for your composers: app/View/Composers

Create a class named SidebarComposer.php:

PHP
namespace App\View\Composers;

use Illuminate\View\View;

class SidebarComposer
{
    public function compose(View $view): void
    {
        #6A9955">// Imagine we are fetching categories from a model
        $view->with('priorities', ['Low', 'Medium', 'High', 'Urgent']);
    }
}

Registering the Composer

To make Laravel aware of this class, we register it in the boot method of our AppServiceProvider. This ensures the logic runs whenever our views are loaded.

Open app/Providers/AppServiceProvider.php:

PHP
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use App\View\Composers\SidebarComposer;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        #6A9955">// Share this data with our specific sidebar partial
        View::composer('partials.sidebar', SidebarComposer::class);
    }
}

Now, every time partials.sidebar.blade.php is included in a view, the $priorities variable will automatically be available. You don't have to pass it from any controller!

Hands-on Exercise

  1. Create the Composer: Follow the steps above to create SidebarComposer.
  2. Update your Sidebar: In your resources/views/partials/sidebar.blade.php, add a loop to display the priorities:
    BLADE
    <ul>
        @foreach($priorities as $priority)
            <li>{{ $priority }}</li>
        @endforeach
    </ul>
  3. Verify: Navigate to any page in your Task Manager that includes this partial. You should see the list populated without having touched your TasksController.

Common Pitfalls

  • Over-composing: Don't put heavy database queries in a View Composer that runs on every page load. Use caching if the data is expensive to fetch, or you'll slow down every request.
  • Namespace Confusion: Ensure your use statements in the Service Provider match the actual namespace of your composer class.
  • The "Global" Trap: Avoid passing massive objects to every view. Be specific. You can use wildcards (e.g., View::composer('tasks.*', ...)), but try to limit the scope to only the views that actually need the data.

Recap

View Composers are a powerful way to keep your controllers lean. By moving shared data logic into dedicated classes, you keep your templates DRY and your application logic organized. We've successfully registered a composer in the AppServiceProvider and injected data into a partial, further modularizing our Task Manager UI.

Up next: Task Manager: Refactoring for Clean Code where we will move business logic out of our controllers and into dedicated Service classes.

Similar Posts