Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

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.

Previous lessonUnderstanding Service ProvidersNext lesson Task Manager: Refactoring for Clean Code
Back to Blog

Similar Posts

LaravelJune 25, 20264 min read

Implementing Blade Partials: A Guide to DRY Laravel Views

Stop repeating yourself in Blade templates. Learn how to implement Blade partials to extract common UI elements and keep your Laravel views maintainable.

Read more
LaravelJune 25, 20263 min read

Customizing Validation Error Messages for Better Laravel UX

Learn to customize Laravel validation error messages to provide clear, helpful feedback to your users. Master field-specific errors and language files.

Part of the course

Laravel Fundamentals: From Zero to Your First App

beginner · Lesson 43 of 52

  1. 1

    Setting Up the Local Development Environment

    4 min
  2. 2

    Installing Laravel and Exploring Directory Structure

    3 min
  3. 3

    Understanding the .env File and Configuration

    3 min
Read more
LaravelJune 25, 20263 min read

Mastering Blade Directives for Loops and Conditionals

Learn how to use Blade directives like @if, @foreach, and @forelse to control your view logic and render dynamic lists in your Laravel applications efficiently.

Read more
  • 4

    The Laravel Application Lifecycle

    4 min
  • 5

    Initializing the Task Manager Project

    3 min
  • 6

    Defining Basic Web Routes

    4 min
  • 7

    Using Route Parameters

    3 min
  • 8

    Creating Your First Controller

    3 min
  • 9

    Returning Responses and Redirects

    3 min
  • 10

    Task Manager: Implementing the Task List Route

    3 min
  • 11

    Introduction to Blade Templating

    3 min
  • 12

    Using Blade Layouts and Sections

    3 min
  • 13

    Implementing Blade Partials

    4 min
  • 14

    Mastering Blade Directives for Loops and Conditionals

    3 min
  • 15

    Task Manager: Building the User Interface

    3 min
  • 16

    Understanding Database Migrations

    3 min
  • 17

    Working with Eloquent Models

    3 min
  • 18

    Performing Basic CRUD Operations

    3 min
  • 19

    Seeding the Database

    3 min
  • 20

    Task Manager: Displaying Real Database Records

    3 min
  • 21

    Capturing User Input from Forms

    4 min
  • 22

    Introduction to Laravel Validation

    3 min
  • 23

    Customizing Validation Error Messages

    3 min
  • 24

    Using Form Requests for Validation

    3 min
  • 25

    Introduction to Authentication

    4 min
  • 26

    Protecting Routes with Middleware

    3 min
  • 27

    Understanding CSRF Protection

    3 min
  • 28

    Preventing Mass Assignment

    3 min
  • 29

    Task Manager: Securing the Application

    3 min
  • 30

    Introduction to Route Model Binding

    3 min
  • 31

    Updating Existing Records

    3 min
  • 32

    Deleting Records

    3 min
  • 33

    Using Named Routes

    3 min
  • 34

    Task Manager: Completing CRUD Functionality

    3 min
  • 35

    Introduction to Database Relationships

    3 min
  • 36

    Querying Related Data

    4 min
  • 37

    Handling File Uploads

    3 min
  • 38

    Using Flash Messages for User Feedback

    3 min
  • 39

    Task Manager: Adding Status and Priorities

    3 min
  • 40

    Introduction to Artisan Commands

    3 min
  • 41

    Debugging with Laravel Tinker

    3 min
  • 42

    Understanding Service Providers

    4 min
  • 43

    Using View Composers

    3 min
  • 44

    Task Manager: Refactoring for Clean Code

    3 min
  • 45

    Introduction to Testing

    3 min
  • 46

    Testing Forms and Validation

    3 min
  • 47

    Using Database Transactions

    Coming soon
  • 48

    Handling Global Exceptions

    Coming soon
  • 49

    Preparing for Production

    Coming soon
  • 50

    Environment Security Best Practices

    Coming soon
  • 51

    Managing Assets in Production

    Coming soon
  • 52

    Task Manager: Deployment Preparation

    Coming soon
  • View full course