Laravel Views: View Composers

View Composers — Are callbacks or class methods that are called when a view is rendered.

If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using class based composers...
        View::composer(
            'profile', 'App\Http\ViewComposers\ProfileComposer'
        );

        // Using Closure based composers...
        View::composer('dashboard', function ($view) {
            //
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use App\Repositories\UserRepository;

class ProfileComposer
{
    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * Create a new profile composer.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        // Dependencies automatically resolved by service container...
        $this->users = $users;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('count', $this->users->count());
    }
}
  • Laravel does not include a default directory for view composers.
  • You are free to organize them however you wish.
  • All view composers are resolved via the service container, so you may type-hint any dependencies you need within a composer's constructor.
  • App/Http/ViewComposers.

Attaching A Composer To Multiple Views

View::composer(
    ['profile', 'dashboard'],
    'App\Http\ViewComposers\MyViewComposer'
);
View::composer('*', function ($view) {
    //
});

You may attach a view composer to multiple views at once by passing an array of views as the first argument to the composer method.

View Creators

View::creator('profile', 'App\Http\ViewCreators\ProfileCreator');
  • Are very similar to view composers.
  • They are executed immediately after the view is instantiated instead of waiting until the view is about to render.
  • To register a view creator, use the creator method.

Laravel Views: View Composers — Structure map

Clickable & Draggable!

Laravel Views: View Composers — Related pages: