Views

Creating Views

Views contain the HTML served by your application and separate your controller / application logic from your presentation logic. Views are stored in the resources/views directory. A simple view might look something like this:

  1. <!-- View stored in resources/views/greeting.blade.php -->
  2. <html>
  3. <body>
  4. <h1>Hello, {{ $name }}</h1>
  5. </body>
  6. </html>

Since this view is stored at resources/views/greeting.blade.php, we may return it using the global view helper like so:

  1. Route::get('/', function () {
  2. return view('greeting', ['name' => 'James']);
  3. });

As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory. The second argument is an array of data that should be made available to the view. In this case, we are passing the name variable, which is displayed in the view using Blade syntax.

Of course, views may also be nested within sub-directories of the resources/views directory. "Dot" notation may be used to reference nested views. For example, if your view is stored at resources/views/admin/profile.blade.php, you may reference it like so:

  1. return view('admin.profile', $data);

Determining If A View Exists

If you need to determine if a view exists, you may use the View facade. The exists method will return true if the view exists:

  1. use Illuminate\Support\Facades\View;
  2. if (View::exists('emails.customer')) {
  3. //
  4. }

Passing Data To Views

As you saw in the previous examples, you may pass an array of data to views:

  1. return view('greetings', ['name' => 'Victoria']);

When passing information in this manner, $data should be an array with key/value pairs. Inside your view, you can then access each value using its corresponding key, such as <?php echo $key; ?>. As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view:

  1. return view('greeting')->with('name', 'Victoria');

Sharing Data With All Views

Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view facade's share method. Typically, you should place calls to share within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\View;
  4. class AppServiceProvider extends ServiceProvider
  5. {
  6. /**
  7. * Bootstrap any application services.
  8. *
  9. * @return void
  10. */
  11. public function boot()
  12. {
  13. View::share('key', 'value');
  14. }
  15. /**
  16. * Register the service provider.
  17. *
  18. * @return void
  19. */
  20. public function register()
  21. {
  22. //
  23. }
  24. }

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.

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\ViewComposers directory:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\View;
  4. use Illuminate\Support\ServiceProvider;
  5. class ComposerServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Register bindings in the container.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. // Using class based composers...
  15. View::composer(
  16. 'profile', 'App\Http\ViewComposers\ProfileComposer'
  17. );
  18. // Using Closure based composers...
  19. View::composer('dashboard', function ($view) {
  20. //
  21. });
  22. }
  23. /**
  24. * Register the service provider.
  25. *
  26. * @return void
  27. */
  28. public function register()
  29. {
  30. //
  31. }
  32. }

{note} 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.

Now that we have registered the composer, the [email protected] method will be executed each time the profile view is being rendered. So, let's define the composer class:

  1. <?php
  2. namespace App\Http\ViewComposers;
  3. use Illuminate\View\View;
  4. use App\Repositories\UserRepository;
  5. class ProfileComposer
  6. {
  7. /**
  8. * The user repository implementation.
  9. *
  10. * @var UserRepository
  11. */
  12. protected $users;
  13. /**
  14. * Create a new profile composer.
  15. *
  16. * @param UserRepository $users
  17. * @return void
  18. */
  19. public function __construct(UserRepository $users)
  20. {
  21. // Dependencies automatically resolved by service container...
  22. $this->users = $users;
  23. }
  24. /**
  25. * Bind data to the view.
  26. *
  27. * @param View $view
  28. * @return void
  29. */
  30. public function compose(View $view)
  31. {
  32. $view->with('count', $this->users->count());
  33. }
  34. }

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.

{tip} All view composers are resolved via the service container, so you may type-hint any dependencies you need within a composer's constructor.

Attaching A Composer To Multiple Views

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:

  1. View::composer(
  2. ['profile', 'dashboard'],
  3. 'App\Http\ViewComposers\MyViewComposer'
  4. );

The composer method also accepts the * character as a wildcard, allowing you to attach a composer to all views:

  1. View::composer('*', function ($view) {
  2. //
  3. });

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:

  1. View::creator('profile', 'App\Http\ViewCreators\ProfileCreator');