Views

Introduction

Of course, it's not practical to return entire HTML documents strings directly from your routes and controllers. Thankfully, views provide a convenient way to place all of our HTML in separate files. Views separate your controller / application logic from your presentation logic and 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 
3<html>
4 <body>
5 <h1>Hello, {{ $name }}</h1>
6 </body>
7</html>
1<!-- View stored in resources/views/greeting.blade.php -->
2 
3<html>
4 <body>
5 <h1>Hello, {{ $name }}</h1>
6 </body>
7</html>

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

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

Looking for more information on how to write Blade templates? Check out the full Blade documentation to get started.

Creating & Rendering Views

You may create a view by placing a file with the .blade.php extension in your application's resources/views directory. The .blade.php extension informs the framework that the file contains a Blade template. Blade templates contain HTML as well as Blade directives that allow you to easily echo values, create "if" statements, iterate over data, and more.

Once you have created a view, you may return it from one of your application's routes or controllers using the global view helper:

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

Views may also be returned using the View facade:

1use Illuminate\Support\Facades\View;
2 
3return View::make('greeting', ['name' => 'James']);
1use Illuminate\Support\Facades\View;
2 
3return View::make('greeting', ['name' => 'James']);

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.

Nested View Directories

Views may also be nested within subdirectories 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 return it from one of your application's routes / controllers like so:

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

View directory names should not contain the . character.

Creating The First Available View

Using the View facade's first method, you may create the first view that exists in a given array of views. This may be useful if your application or package allows views to be customized or overwritten:

1use Illuminate\Support\Facades\View;
2 
3return View::first(['custom.admin', 'admin'], $data);
1use Illuminate\Support\Facades\View;
2 
3return View::first(['custom.admin', 'admin'], $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:

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

Passing Data To Views

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

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

When passing information in this manner, the data should be an array with key / value pairs. After providing data to a view, you can then access each value within your view using the data's keys, such as <?php echo $name; ?>.

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. The with method returns an instance of the view object so that you can continue chaining methods before returning the view:

1return view('greeting')
2 ->with('name', 'Victoria')
3 ->with('occupation', 'Astronaut');
1return view('greeting')
2 ->with('name', 'Victoria')
3 ->with('occupation', 'Astronaut');

Sharing Data With All Views

Occasionally, you may need to share 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 the share method within a service provider's boot method. You are free to add them to the App\Providers\AppServiceProvider class or generate a separate service provider to house them:

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

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. View composers may prove particularly useful if the same view is returned by multiple routes or controllers within your application and always needs a particular piece of data.

Typically, view composers will be registered within one of your application's service providers. In this example, we'll assume that we have created a new App\Providers\ViewServiceProvider to house this logic.

We'll use the View facade's composer method to register the view composer. Laravel does not include a default directory for class based view composers, so you are free to organize them however you wish. For example, you could create an app/View/Composers directory to house all of your application's view composers:

1<?php
2 
3namespace App\Providers;
4 
5use App\View\Composers\ProfileComposer;
6use Illuminate\Support\Facades\View;
7use Illuminate\Support\ServiceProvider;
8 
9class ViewServiceProvider extends ServiceProvider
10{
11 /**
12 * Register any application services.
13 *
14 * @return void
15 */
16 public function register()
17 {
18 //
19 }
20 
21 /**
22 * Bootstrap any application services.
23 *
24 * @return void
25 */
26 public function boot()
27 {
28 // Using class based composers...
29 View::composer('profile', ProfileComposer::class);
30 
31 // Using closure based composers...
32 View::composer('dashboard', function ($view) {
33 //
34 });
35 }
36}
1<?php
2 
3namespace App\Providers;
4 
5use App\View\Composers\ProfileComposer;
6use Illuminate\Support\Facades\View;
7use Illuminate\Support\ServiceProvider;
8 
9class ViewServiceProvider extends ServiceProvider
10{
11 /**
12 * Register any application services.
13 *
14 * @return void
15 */
16 public function register()
17 {
18 //
19 }
20 
21 /**
22 * Bootstrap any application services.
23 *
24 * @return void
25 */
26 public function boot()
27 {
28 // Using class based composers...
29 View::composer('profile', ProfileComposer::class);
30 
31 // Using closure based composers...
32 View::composer('dashboard', function ($view) {
33 //
34 });
35 }
36}
exclamation

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 compose method of the App\View\Composers\ProfileComposer class will be executed each time the profile view is being rendered. Let's take a look at an example of the composer class:

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

As you can see, 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:

1use App\Views\Composers\MultiComposer;
2 
3View::composer(
4 ['profile', 'dashboard'],
5 MultiComposer::class
6);
1use App\Views\Composers\MultiComposer;
2 
3View::composer(
4 ['profile', 'dashboard'],
5 MultiComposer::class
6);

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

1View::composer('*', function ($view) {
2 //
3});
1View::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:

1use App\View\Creators\ProfileCreator;
2use Illuminate\Support\Facades\View;
3 
4View::creator('profile', ProfileCreator::class);
1use App\View\Creators\ProfileCreator;
2use Illuminate\Support\Facades\View;
3 
4View::creator('profile', ProfileCreator::class);

Optimizing Views

By default, Blade template views are compiled on demand. When a request is executed that renders a view, Laravel will determine if a compiled version of the view exists. If the file exists, Laravel will then determine if the uncompiled view has been modified more recently than the compiled view. If the compiled view either does not exist, or the uncompiled view has been modified, Laravel will recompile the view.

Compiling views during the request may have a small negative impact on performance, so Laravel provides the view:cache Artisan command to precompile all of the views utilized by your application. For increased performance, you may wish to run this command as part of your deployment process:

1php artisan view:cache
1php artisan view:cache

You may use the view:clear command to clear the view cache:

1php artisan view:clear
1php artisan view:clear

Comments

No Comments Yet

“Laravel” is a Trademark of Taylor Otwell.
The source documentation is released under MIT license. See laravel/docs on GitHub for details.
The translated documentations are released under MIT license. See cornch/laravel-docs-l10n on GitHub for details.