Mahamudul Hasan Rubel
HomeAboutProjectsSkillsExperienceBlogPhotosContact
Mahamudul Hasan Rubel

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

Navigation

  • Home
  • About
  • Projects
  • Skills
  • Experience
  • Blog
  • 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
LaravelPHPJune 21, 20264 min read

Mastering Laravel View Composers: Injecting Shared Data Across Your Templates

Laravel view composers allow you to inject data into Blade templates efficiently. Learn to share data globally or selectively without bloating your controllers.

laravelphpbladedesign-patternsbackend-developmentTutorial
Close-up of software development tools displaying code and version control systems on a computer monitor.

I remember staring at a controller method that was 80 lines long, mostly because I was manually fetching the same "recent posts" list and "categories" array just to populate the sidebar. It was a mess, and I knew there had to be a better way to handle laravel shared view data than repeating those database calls in every single controller method.

If you’ve ever found yourself passing the same variables into view() across five different controllers, you’re doing it the hard way. View composers are the elegant solution for this exact problem.

What are Laravel View Composers?

At their core, laravel view composers are callbacks or class methods that fire when a view is rendered. They allow you to "compose" data into a view right before it hits the browser. Instead of your controller being responsible for fetching data for the entire page, the composer handles the specific requirements of that view fragment.

Think of it as a middleware for your templates. You define the logic once, and Laravel ensures it’s executed whenever a specific view—or set of views—is requested.

The Wrong Turn: View Sharing Globally

A close-up of a red wrong way road sign against an overcast sky, symbolizing caution.

When I first started with Laravel, I abused the View::share() method in my AppServiceProvider. It felt like a shortcut.

PHP
#6A9955">// Don't do this in a production app
public function boot()
{
    View::share('categories', Category::all());
}

While this works, it’s a performance nightmare. That code runs on every single request, even on pages where the sidebar doesn't exist. You’re fetching data from the database that you never actually use. I once spent about two days refactoring a legacy project where this exact pattern added roughly 150ms of overhead to every request because of unnecessary Eloquent queries.

Implementing a Proper View Composer

To do this right, we use a service provider to register our composer. This is a great way to practice Laravel Service Providers: A Practical Guide to Clean Architecture by keeping your application logic modular.

1. Create the Composer Class

First, create a dedicated class to handle the logic. I usually keep these in app/View/Composers.

PHP
namespace App\View\Composers;

use App\Models\Category;
use Illuminate\View\View;

class SidebarComposer
{
    public function compose(View $view)
    {
        $view->with('categories', Category::limit(10)->get());
    }
}

2. Register it in a Service Provider

Open your AppServiceProvider (or a dedicated ViewServiceProvider if you have many) and register the composer in the boot method.

PHP
public function boot()
{
    \Illuminate\Support\Facades\View::composer(
        ['layouts.sidebar', 'partials.nav'], 
        \App\View\Composers\SidebarComposer::class
    );
}

By passing an array, we target specific views. The logic only triggers when one of those files is rendered. This is much cleaner than global sharing.

Leveraging Laravel Dependency Injection

One of the best parts about using a class-based composer is that it supports laravel dependency injection. If your composer needs a service to calculate data, you can type-hint it in the constructor, just like you would in a controller or job.

If you aren't familiar with how the container resolves these, check out Laravel Service Container: A Beginner’s Guide to Dependency Injection.

PHP
namespace App\View\Composers;

use App\Services\CategoryService;
use Illuminate\View\View;

class SidebarComposer
{
    protected $categories;

    public function __construct(CategoryService $service)
    {
        $this->categories = $service->getPopularCategories();
    }

    public function compose(View $view)
    {
        $view->with('categories', $this->categories);
    }
}

Because the service is injected, your composer remains testable. You can easily mock CategoryService in your unit tests.

Common Patterns and Gotchas

When using these blade templates tools, keep these tips in mind:

  • Caching is your friend: If your composer fetches data from an API or a heavy database query, wrap the result in Cache::remember(). Since composers run frequently, you don't want them to become a bottleneck.
  • Wildcards work: You can use a wildcard to target all views in a folder: View::composer('admin.*', AdminComposer::class).
  • Keep it thin: Don't put business logic inside the composer. The composer's only job is to fetch the data and pass it to the view. If you find yourself writing complex logic, move it into a Service or a Repository class.

Frequently Asked Questions

Can I use a closure instead of a class? Yes. For simple data, you can use View::composer('view.name', function ($view) { ... }); directly in your service provider. Use classes once the logic grows beyond a few lines.

How is this different from View Composers and View Creators? Composers run after the view is instantiated but before it's rendered. Creators run immediately after the view is instantiated. 99% of the time, you want a Composer.

Do view composers work with Livewire? Yes, but be careful. Livewire components often manage their own state. If you find yourself fighting with data being overwritten, you might be better off using a standard Livewire mount method or a dedicated component.

Closing Thoughts

A close-up of hands writing a heartfelt note on a card, showcasing personal connection.

Mastering laravel design patterns like view composers is a rite of passage for moving from "making it work" to "making it maintainable." My biggest mistake early on was trying to force everything into controllers. Once I started offloading view-specific data fetching to composers, my controllers became significantly lighter and easier to read.

I'm still occasionally tempted to just use View::share() for quick prototypes, but I always regret it later. Stick to the composer classes—your future self will thank you when you're debugging that sidebar three months from now.

Back to Blog

Similar Posts

A minimalist photo of a card with 'Big Data' text inside a green envelope, showcasing modern concepts.
LaravelPHPJune 21, 20264 min read

Laravel Database Transactions: A Guide to Data Integrity

Master laravel database transactions to ensure your application remains consistent. Learn how to implement atomic operations and avoid partial data updates.

Read more
A vibrant orange arrow on a tree indicates direction in the forest.
LaravelPHPJune 21, 20264 min read

Laravel Eloquent Accessors and Mutators: A Practical Guide

Master Laravel eloquent accessors and mutators to transform data on the fly. Learn how to clean, format, and prepare your model attributes like a pro.

Read more
A large crowd of tourists lines up in sunny St. Peter's Square, showcasing architectural columns.
LaravelPHPJune 21, 20264 min read

Mastering Laravel Queues: A Beginner’s Guide to Background Processing

Mastering Laravel queues helps you move slow tasks to the background. Learn how to implement background jobs to boost your PHP performance and app reliability.

Read more