For this example, let's register the view composers within a service provider. We'll use the View
facade to access the underlying Illuminate\Contracts\View\Factory
contract implementation. Remember, Laravel does not include a default directory for view composers. You are free to organize them however you wish. For example, you could create an app/Http/View/Composers
directory:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
}
}
Remember, if you create a new service provider to contain your view composer registrations, you will need to add the service provider to the providers
array in the config/app.php
configuration file.
ProfileComposer@compose
method will be executed each time the profile
view is being rendered. So, let's define the composer class:
<?php
namespace App\Http\View\Composers;
use App\Repositories\UserRepository;
use Illuminate\View\View;
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());
}
}
Just before the view is rendered, the composer's compose
method is called with the Illuminate\View \View
instance. You may use the with
method to bind data to the view.
composer
method:
View::composer(
['profile', 'dashboard'],
'App\Http\View\Composers\MyViewComposer'
);
The composer
method also accepts the *
character as a wildcard, allowing you to attach a composer to all views:
View::composer('*', function ($view) {
//
});
View Creators
View creators are very similar to view composers; however, 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:
View::creator('profile', 'App\Http\View\Creators\ProfileCreator');