Blade Templates

Introduction

Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

Template Inheritance

Defining A Layout

Two of the primary benefits of using Blade are template inheritance and sections. To get started, let’s take a look at a simple example. First, we will examine a “master” page layout. Since most web applications maintain the same general layout across various pages, it’s convenient to define this layout as a single Blade view:

  1. <!-- Stored in resources/views/layouts/app.blade.php -->
  2. <html>
  3. <head>
  4. <title>App Name - @yield('title')</title>
  5. </head>
  6. <body>
  7. @section('sidebar')
  8. This is the master sidebar.
  9. @show
  10. <div class="container">
  11. @yield('content')
  12. </div>
  13. </body>
  14. </html>

As you can see, this file contains typical HTML mark-up. However, take note of the @section and @yield directives. The @section directive, as the name implies, defines a section of content, while the @yield directive is used to display the contents of a given section.

Now that we have defined a layout for our application, let’s define a child page that inherits the layout.

Extending A Layout

When defining a child view, use the Blade @extends directive to specify which layout the child view should “inherit”. Views which extend a Blade layout may inject content into the layout’s sections using @section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:

  1. <!-- Stored in resources/views/child.blade.php -->
  2. @extends('layouts.app')
  3. @section('title', 'Page Title')
  4. @section('sidebar')
  5. @parent
  6. <p>This is appended to the master sidebar.</p>
  7. @endsection
  8. @section('content')
  9. <p>This is my body content.</p>
  10. @endsection

In this example, the sidebar section is utilizing the @parent directive to append (rather than overwriting) content to the layout’s sidebar. The @parent directive will be replaced by the content of the layout when the view is rendered.

{tip} Contrary to the previous example, this sidebar section ends with @endsection instead of @show. The @endsection directive will only define a section while @show will define and immediately yield the section.

The @yield directive also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined:

  1. @yield('content', View::make('view.name'))

Blade views may be returned from routes using the global view helper:

  1. Route::get('blade', function () {
  2. return view('child');
  3. });

Displaying Data

You may display data passed to your Blade views by wrapping the variable in curly braces. For example, given the following route:

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

You may display the contents of the name variable like so:

  1. Hello, {{ $name }}.

{tip} Blade {{ }} statements are automatically sent through PHP’s htmlspecialchars function to prevent XSS attacks.

You are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo statement:

  1. The current UNIX timestamp is {{ time() }}.

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through PHP’s htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

  1. Hello, {!! $name !!}.

{note} Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

Rendering JSON

Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:

  1. <script>
  2. var app = <?php echo json_encode($array); ?>;
  3. </script>

However, instead of manually calling json_encode, you may use the @json Blade directive. The @json directive accepts the same arguments as PHP’s json_encode function:

  1. <script>
  2. var app = @json($array);
  3. var app = @json($array, JSON_PRETTY_PRINT);
  4. </script>

{note} You should only use the @json directive to render existing variables as JSON. The Blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures.

HTML Entity Encoding

By default, Blade (and the Laravel e helper) will double encode HTML entities. If you would like to disable double encoding, call the Blade::withoutDoubleEncoding method from the boot method of your AppServiceProvider:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\Blade;
  4. use Illuminate\Support\ServiceProvider;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Bootstrap any application services.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. Blade::withoutDoubleEncoding();
  15. }
  16. }

Blade & JavaScript Frameworks

Since many JavaScript frameworks also use “curly” braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

  1. <h1>Laravel</h1>
  2. Hello, @{{ name }}.

In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.

The @ symbol may also be used to escape Blade directives:

  1. {{-- Blade --}}
  2. @@json()
  3. <!-- HTML output -->
  4. @json()

The @verbatim Directive

If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the @verbatim directive so that you do not have to prefix each Blade echo statement with an @ symbol:

  1. @verbatim
  2. <div class="container">
  3. Hello, {{ name }}.
  4. </div>
  5. @endverbatim

Control Structures

In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.

If Statements

You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts:

  1. @if (count($records) === 1)
  2. I have one record!
  3. @elseif (count($records) > 1)
  4. I have multiple records!
  5. @else
  6. I don't have any records!
  7. @endif

For convenience, Blade also provides an @unless directive:

  1. @unless (Auth::check())
  2. You are not signed in.
  3. @endunless

In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions:

  1. @isset($records)
  2. // $records is defined and is not null...
  3. @endisset
  4. @empty($records)
  5. // $records is "empty"...
  6. @endempty

Authentication Directives

The @auth and @guest directives may be used to quickly determine if the current user is authenticated or is a guest:

  1. @auth
  2. // The user is authenticated...
  3. @endauth
  4. @guest
  5. // The user is not authenticated...
  6. @endguest

If needed, you may specify the authentication guard that should be checked when using the @auth and @guest directives:

  1. @auth('admin')
  2. // The user is authenticated...
  3. @endauth
  4. @guest('admin')
  5. // The user is not authenticated...
  6. @endguest

Section Directives

You may check if a section has content using the @hasSection directive:

  1. @hasSection('navigation')
  2. <div class="pull-right">
  3. @yield('navigation')
  4. </div>
  5. <div class="clearfix"></div>
  6. @endif

You may use the sectionMissing directive to determine if a section does not have content:

  1. @sectionMissing('navigation')
  2. <div class="pull-right">
  3. @include('default-navigation')
  4. </div>
  5. @endif

Environment Directives

You may check if the application is running in the production environment using the @production directive:

  1. @production
  2. // Production specific content...
  3. @endproduction

Or, you may determine if the application is running in a specific environment using the @env directive:

  1. @env('staging')
  2. // The application is running in "staging"...
  3. @endenv
  4. @env(['staging', 'production'])
  5. // The application is running in "staging" or "production"...
  6. @endenv

Switch Statements

Switch statements can be constructed using the @switch, @case, @break, @default and @endswitch directives:

  1. @switch($i)
  2. @case(1)
  3. First case...
  4. @break
  5. @case(2)
  6. Second case...
  7. @break
  8. @default
  9. Default case...
  10. @endswitch

Loops

In addition to conditional statements, Blade provides simple directives for working with PHP’s loop structures. Again, each of these directives functions identically to their PHP counterparts:

  1. @for ($i = 0; $i < 10; $i++)
  2. The current value is {{ $i }}
  3. @endfor
  4. @foreach ($users as $user)
  5. <p>This is user {{ $user->id }}</p>
  6. @endforeach
  7. @forelse ($users as $user)
  8. <li>{{ $user->name }}</li>
  9. @empty
  10. <p>No users</p>
  11. @endforelse
  12. @while (true)
  13. <p>I'm looping forever.</p>
  14. @endwhile

{tip} When looping, you may use the loop variable to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop.

When using loops you may also end the loop or skip the current iteration:

  1. @foreach ($users as $user)
  2. @if ($user->type == 1)
  3. @continue
  4. @endif
  5. <li>{{ $user->name }}</li>
  6. @if ($user->number == 5)
  7. @break
  8. @endif
  9. @endforeach

You may also include the condition with the directive declaration in one line:

  1. @foreach ($users as $user)
  2. @continue($user->type == 1)
  3. <li>{{ $user->name }}</li>
  4. @break($user->number == 5)
  5. @endforeach

The Loop Variable

When looping, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

  1. @foreach ($users as $user)
  2. @if ($loop->first)
  3. This is the first iteration.
  4. @endif
  5. @if ($loop->last)
  6. This is the last iteration.
  7. @endif
  8. <p>This is user {{ $user->id }}</p>
  9. @endforeach

If you are in a nested loop, you may access the parent loop’s $loop variable via the parent property:

  1. @foreach ($users as $user)
  2. @foreach ($user->posts as $post)
  3. @if ($loop->parent->first)
  4. This is first iteration of the parent loop.
  5. @endif
  6. @endforeach
  7. @endforeach

The $loop variable also contains a variety of other useful properties:

PropertyDescription
$loop->indexThe index of the current loop iteration (starts at 0).
$loop->iterationThe current loop iteration (starts at 1).
$loop->remainingThe iterations remaining in the loop.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration through the loop.
$loop->lastWhether this is the last iteration through the loop.
$loop->evenWhether this is an even iteration through the loop.
$loop->oddWhether this is an odd iteration through the loop.
$loop->depthThe nesting level of the current loop.
$loop->parentWhen in a nested loop, the parent’s loop variable.

Comments

Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application:

  1. {{-- This comment will not be present in the rendered HTML --}}

PHP

In some situations, it’s useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template:

  1. @php
  2. //
  3. @endphp

{tip} While Blade provides this feature, using it frequently may be a signal that you have too much logic embedded within your template.

The @once Directive

The @once directive allows you to define a portion of the template that will only be evaluate once per rendering cycle. This may be useful for pushing a given piece of JavaScript into the page’s header using stacks. For example, if you are rendering a given component within a loop, you may wish to only push the JavaScript to the header the the first time the component is rendered:

  1. @once
  2. @push('scripts')
  3. <script>
  4. // Your custom JavaScript...
  5. </script>
  6. @endpush
  7. @endonce

Forms

CSRF Field

Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the @csrf Blade directive to generate the token field:

  1. <form method="POST" action="/profile">
  2. @csrf
  3. ...
  4. </form>

Method Field

Since HTML forms can’t make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for you:

  1. <form action="/foo/bar" method="POST">
  2. @method('PUT')
  3. ...
  4. </form>

Validation Errors

The @error directive may be used to quickly check if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

  1. <!-- /resources/views/post/create.blade.php -->
  2. <label for="title">Post Title</label>
  3. <input id="title" type="text" class="@error('title') is-invalid @enderror">
  4. @error('title')
  5. <div class="alert alert-danger">{{ $message }}</div>
  6. @enderror

You may pass the name of a specific error bag as the second parameter to the @error directive to retrieve validation error messages on pages containing multiple forms:

  1. <!-- /resources/views/auth.blade.php -->
  2. <label for="email">Email address</label>
  3. <input id="email" type="email" class="@error('email', 'login') is-invalid @enderror">
  4. @error('email', 'login')
  5. <div class="alert alert-danger">{{ $message }}</div>
  6. @enderror

Components

Components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. There are two approaches to writing components: class based components and anonymous components.

To create a class based component, you may use the make:component Artisan command. To illustrate how to use components, we will create a simple Alert component. The make:component command will place the component in the App\View\Components directory:

  1. php artisan make:component Alert

The make:component command will also create a view template for the component. The view will be placed in the resources/views/components directory.

Manually Registering Package Components

When writing components for your own application, components are automatically discovered within the app/View/Components directory and resources/views/components directory.

However, if you are building a package that utilizes Blade components, you will need to manually register your component class and its HTML tag alias. You should typically register your components in the boot method of your package’s service provider:

  1. use Illuminate\Support\Facades\Blade;
  2. /**
  3. * Bootstrap your package's services.
  4. */
  5. public function boot()
  6. {
  7. Blade::component('package-alert', AlertComponent::class);
  8. }

Once your component has been registered, it may be rendered using its tag alias:

  1. <x-package-alert/>

Alternatively, you may use the componentNamespace method to autoload component classes by convention. For example, a Nightshade package might have Calendar and ColorPicker components that reside within the Package\Views\Components namespace:

  1. use Illuminate\Support\Facades\Blade;
  2. /**
  3. * Bootstrap your package's services.
  4. */
  5. public function boot()
  6. {
  7. Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade');
  8. }

This will allow the usage of package components by their vendor namespace using the package-name:: syntax:

  1. <x-nightshade::calendar />
  2. <x-nightshade::color-picker />

Blade will automatically detect the class that’s linked to this component by pascal-casing the component name. Subdirectories are also supported using “dot” notation.

Displaying Components

To display a component, you may use a Blade component tag within one of your Blade templates. Blade component tags start with the string x- followed by the kebab case name of the component class:

  1. <x-alert/>
  2. <x-user-profile/>

If the component class is nested deeper within the App\View\Components directory, you may use the . character to indicate directory nesting. For example, if we assume a component is located at App\View\Components\Inputs\Button.php, we may render it like so:

  1. <x-inputs.button/>

Passing Data To Components

You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attributes. PHP expressions and variables should be passed to the component via attributes that use the : character as a prefix:

  1. <x-alert type="error" :message="$message"/>

You should define the component’s required data in its class constructor. All public properties on a component will automatically be made available to the component’s view. It is not necessary to pass the data to the view from the component’s render method:

  1. <?php
  2. namespace App\View\Components;
  3. use Illuminate\View\Component;
  4. class Alert extends Component
  5. {
  6. /**
  7. * The alert type.
  8. *
  9. * @var string
  10. */
  11. public $type;
  12. /**
  13. * The alert message.
  14. *
  15. * @var string
  16. */
  17. public $message;
  18. /**
  19. * Create the component instance.
  20. *
  21. * @param string $type
  22. * @param string $message
  23. * @return void
  24. */
  25. public function __construct($type, $message)
  26. {
  27. $this->type = $type;
  28. $this->message = $message;
  29. }
  30. /**
  31. * Get the view / contents that represent the component.
  32. *
  33. * @return \Illuminate\View\View|\Closure|string
  34. */
  35. public function render()
  36. {
  37. return view('components.alert');
  38. }
  39. }

When your component is rendered, you may display the contents of your component’s public variables by echoing the variables by name:

  1. <div class="alert alert-{{ $type }}">
  2. {{ $message }}
  3. </div>

Casing

Component constructor arguments should be specified using camelCase, while kebab-case should be used when referencing the argument names in your HTML attributes. For example, given the following component constructor:

  1. /**
  2. * Create the component instance.
  3. *
  4. * @param string $alertType
  5. * @return void
  6. */
  7. public function __construct($alertType)
  8. {
  9. $this->alertType = $alertType;
  10. }

The $alertType argument may be provided like so:

  1. <x-alert alert-type="danger" />

Component Methods

In addition to public variables being available to your component template, any public methods on the component may also be executed. For example, imagine a component that has a isSelected method:

  1. /**
  2. * Determine if the given option is the current selected option.
  3. *
  4. * @param string $option
  5. * @return bool
  6. */
  7. public function isSelected($option)
  8. {
  9. return $option === $this->selected;
  10. }

You may execute this method from your component template by invoking the variable matching the name of the method:

  1. <option {{ $isSelected($value) ? 'selected="selected"' : '' }} value="{{ $value }}">
  2. {{ $label }}
  3. </option>

Using Attributes & Slots Inside The Class

Blade components also allow you to access the component name, attributes, and slot inside the class’s render method. However, in order to access this data, you should return a Closure from your component’s render method. The Closure will receive a $data array as its only argument:

  1. /**
  2. * Get the view / contents that represent the component.
  3. *
  4. * @return \Illuminate\View\View|\Closure|string
  5. */
  6. public function render()
  7. {
  8. return function (array $data) {
  9. // $data['componentName'];
  10. // $data['attributes'];
  11. // $data['slot'];
  12. return '<div>Component content</div>';
  13. };
  14. }

The componentName is equal to the name used in the HTML tag after the x- prefix. So <x-alert />‘s componentName will be alert. The attributes element will contain all of the attributes that were present on the HTML tag. The slot element is a Illuminate\Support\HtmlString instance with the contents of the slot from the component.

Additional Dependencies

If your component requires dependencies from Laravel’s service container, you may list them before any of the component’s data attributes and they will automatically be injected by the container:

  1. use App\Services\AlertCreator
  2. /**
  3. * Create the component instance.
  4. *
  5. * @param \App\Services\AlertCreator $creator
  6. * @param string $type
  7. * @param string $message
  8. * @return void
  9. */
  10. public function __construct(AlertCreator $creator, $type, $message)
  11. {
  12. $this->creator = $creator;
  13. $this->type = $type;
  14. $this->message = $message;
  15. }

Managing Attributes

We’ve already examined how to pass data attributes to a component; however, sometimes you may need to specify additional HTML attributes, such as class, that are not part of the data required for a component to function. Typically, you want to pass these additional attributes down to the root element of the component template. For example, imagine we want to render an alert component like so:

  1. <x-alert type="error" :message="$message" class="mt-4"/>

All of the attributes that are not part of the component’s constructor will automatically be added to the component’s “attribute bag”. This attribute bag is automatically made available to the component via the $attributes variable. All of the attributes may be rendered within the component by echoing this variable:

  1. <div {{ $attributes }}>
  2. <!-- Component Content -->
  3. </div>

{note} Using directives such as @env directly on a component is not supported at this time.

Default / Merged Attributes

Sometimes you may need to specify default values for attributes or merge additional values into some of the component’s attributes. To accomplish this, you may use the attribute bag’s merge method:

  1. <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
  2. {{ $message }}
  3. </div>

If we assume this component is utilized like so:

  1. <x-alert type="error" :message="$message" class="mb-4"/>

The final, rendered HTML of the component will appear like the following:

  1. <div class="alert alert-error mb-4">
  2. <!-- Contents of the $message variable -->
  3. </div>

Filtering Attributes

You may filter attributes using the filter method. This method accepts a Closure which should return true if you wish to retain the attribute in the attribute bag:

  1. {{ $attributes->filter(fn ($value, $key) => $key == 'foo') }}

For convenience, you may use the whereStartsWith method to retrieve all attributes whose keys begin with a given string:

  1. {{ $attributes->whereStartsWith('wire:model') }}

Using the first method, you may render the first attribute in a given attribute bag:

  1. {{ $attributes->whereStartsWith('wire:model')->first() }}

Slots

Often, you will need to pass additional content to your component via “slots”. Let’s imagine that an alert component we created has the following markup:

  1. <!-- /resources/views/components/alert.blade.php -->
  2. <div class="alert alert-danger">
  3. {{ $slot }}
  4. </div>

We may pass content to the slot by injecting content into the component:

  1. <x-alert>
  2. <strong>Whoops!</strong> Something went wrong!
  3. </x-alert>

Sometimes a component may need to render multiple different slots in different locations within the component. Let’s modify our alert component to allow for the injection of a “title”:

  1. <!-- /resources/views/components/alert.blade.php -->
  2. <span class="alert-title">{{ $title }}</span>
  3. <div class="alert alert-danger">
  4. {{ $slot }}
  5. </div>

You may define the content of the named slot using the x-slot tag. Any content not within a x-slot tag will be passed to the component in the $slot variable:

  1. <x-alert>
  2. <x-slot name="title">
  3. Server Error
  4. </x-slot>
  5. <strong>Whoops!</strong> Something went wrong!
  6. </x-alert>

Scoped Slots

If you have used a JavaScript framework such as Vue, you may be familiar with “scoped slots”, which allow you to access data or methods from the component within your slot. You may achieve similar behavior in Laravel by defining public methods or properties on your component and accessing the component within your slot via the $component variable:

  1. <x-alert>
  2. <x-slot name="title">
  3. {{ $component->formatAlert('Server Error') }}
  4. </x-slot>
  5. <strong>Whoops!</strong> Something went wrong!
  6. </x-alert>

Inline Component Views

For very small components, it may feel cumbersome to manage both the component class and the component’s view template. For this reason, you may return the component’s markup directly from the render method:

  1. /**
  2. * Get the view / contents that represent the component.
  3. *
  4. * @return \Illuminate\View\View|\Closure|string
  5. */
  6. public function render()
  7. {
  8. return <<<'blade'
  9. <div class="alert alert-danger">
  10. {{ $slot }}
  11. </div>
  12. blade;
  13. }

Generating Inline View Components

To create a component that renders an inline view, you may use the inline option when executing the make:component command:

  1. php artisan make:component Alert --inline

Anonymous Components

Similar to inline components, anonymous components provide a mechanism for managing a component via a single file. However, anonymous components utilize a single view file and have no associated class. To define an anonymous component, you only need to place a Blade template within your resources/views/components directory. For example, assuming you have defined a component at resources/views/components/alert.blade.php:

  1. <x-alert/>

You may use the . character to indicate if a component is nested deeper inside the components directory. For example, assuming the component is defined at resources/views/components/inputs/button.blade.php, you may render it like so:

  1. <x-inputs.button/>

Data Properties / Attributes

Since anonymous components do not have any associated class, you may wonder how you may differentiate which data should be passed to the component as variables and which attributes should be placed in the component’s attribute bag.

You may specify which attributes should be considered data variables using the @props directive at the top of your component’s Blade template. All other attributes on the component will be available via the component’s attribute bag. If you wish to give a data variable a default value, you may specify the variable’s name as the array key and the default value as the array value:

  1. <!-- /resources/views/components/alert.blade.php -->
  2. @props(['type' => 'info', 'message'])
  3. <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
  4. {{ $message }}
  5. </div>

Dynamic Components

Sometimes you may need to render a component but not know which component should be rendered until runtime. In this situation, you may use Laravel’s built-in dynamic-component component to render the component based on a runtime value or variable:

  1. <x-dynamic-component :component="$componentName" class="mt-4" />

Including Subviews

Blade’s @include directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:

  1. <div>
  2. @include('shared.errors')
  3. <form>
  4. <!-- Form Contents -->
  5. </form>
  6. </div>

Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

  1. @include('view.name', ['some' => 'data'])

If you attempt to @include a view which does not exist, Laravel will throw an error. If you would like to include a view that may or may not be present, you should use the @includeIf directive:

  1. @includeIf('view.name', ['some' => 'data'])

If you would like to @include a view if a given boolean expression evaluates to true, you may use the @includeWhen directive:

  1. @includeWhen($boolean, 'view.name', ['some' => 'data'])

If you would like to @include a view if a given boolean expression evaluates to false, you may use the @includeUnless directive:

  1. @includeUnless($boolean, 'view.name', ['some' => 'data'])

To include the first view that exists from a given array of views, you may use the includeFirst directive:

  1. @includeFirst(['custom.admin', 'admin'], ['some' => 'data'])

{note} You should avoid using the __DIR__ and __FILE__ constants in your Blade views, since they will refer to the location of the cached, compiled view.

Aliasing Includes

If your Blade includes are stored in a subdirectory, you may wish to alias them for easier access. For example, imagine a Blade include that is stored at resources/views/includes/input.blade.php with the following content:

  1. <input type="{{ $type ?? 'text' }}">

You may use the include method to alias the include from includes.input to input. Typically, this should be done in the boot method of your AppServiceProvider:

  1. use Illuminate\Support\Facades\Blade;
  2. Blade::include('includes.input', 'input');

Once the include has been aliased, you may render it using the alias name as the Blade directive:

  1. @input(['type' => 'email'])

Rendering Views For Collections

You may combine loops and includes into one line with Blade’s @each directive:

  1. @each('view.name', $jobs, 'job')

The first argument is the view partial to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of jobs, typically you will want to access each job as a job variable within your view partial. The key for the current iteration will be available as the key variable within your view partial.

You may also pass a fourth argument to the @each directive. This argument determines the view that will be rendered if the given array is empty.

  1. @each('view.name', $jobs, 'job', 'view.empty')

{note} Views rendered via @each do not inherit the variables from the parent view. If the child view requires these variables, you should use @foreach and @include instead.

Stacks

Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views:

  1. @push('scripts')
  2. <script src="/example.js"></script>
  3. @endpush

You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the @stack directive:

  1. <head>
  2. <!-- Head Contents -->
  3. @stack('scripts')
  4. </head>

If you would like to prepend content onto the beginning of a stack, you should use the @prepend directive:

  1. @push('scripts')
  2. This will be second...
  3. @endpush
  4. // Later...
  5. @prepend('scripts')
  6. This will be first...
  7. @endprepend

Service Injection

The @inject directive may be used to retrieve a service from the Laravel service container. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve:

  1. @inject('metrics', 'App\Services\MetricsService')
  2. <div>
  3. Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
  4. </div>

Extending Blade

Blade allows you to define your own custom directives using the directive method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains.

The following example creates a @datetime($var) directive which formats a given $var, which should be an instance of DateTime:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\Blade;
  4. use Illuminate\Support\ServiceProvider;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Register any application services.
  9. *
  10. * @return void
  11. */
  12. public function register()
  13. {
  14. //
  15. }
  16. /**
  17. * Bootstrap any application services.
  18. *
  19. * @return void
  20. */
  21. public function boot()
  22. {
  23. Blade::directive('datetime', function ($expression) {
  24. return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
  25. });
  26. }
  27. }

As you can see, we will chain the format method onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be:

  1. <?php echo ($var)->format('m/d/Y H:i'); ?>

{note} After updating the logic of a Blade directive, you will need to delete all of the cached Blade views. The cached Blade views may be removed using the view:clear Artisan command.

Custom If Statements

Programming a custom directive is sometimes more complex than necessary when defining simple, custom conditional statements. For that reason, Blade provides a Blade::if method which allows you to quickly define custom conditional directives using Closures. For example, let’s define a custom conditional that checks the current application cloud provider. We may do this in the boot method of our AppServiceProvider:

  1. use Illuminate\Support\Facades\Blade;
  2. /**
  3. * Bootstrap any application services.
  4. *
  5. * @return void
  6. */
  7. public function boot()
  8. {
  9. Blade::if('cloud', function ($provider) {
  10. return config('filesystems.default') === $provider;
  11. });
  12. }

Once the custom conditional has been defined, we can easily use it on our templates:

  1. @cloud('digitalocean')
  2. // The application is using the digitalocean cloud provider...
  3. @elsecloud('aws')
  4. // The application is using the aws provider...
  5. @else
  6. // The application is not using the digitalocean or aws environment...
  7. @endcloud
  8. @unlesscloud('aws')
  9. // The application is not using the aws environment...
  10. @endcloud