Blade
Blade
Introduction
Template Inheritance
Defining A Layout
Extending A Layout
Displaying Data
If Statements
Switch Statements
Loops
The Loop Variable
Comments
PHP
Forms
CSRF Field
Method Field
Validation Errors
Components
Displaying Components
Passing Data To Components
Managing Attributes
Slots
Inline Component Views
Anonymous Components
Including Subviews
Service Injection
Extending Blade
Custom If Statements
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:
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 @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:
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:
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>
1 <script>
2 var app = @json($array);
3
4 var app = @json($array, JSON_PRETTY_PRINT);
5 </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.
1 <?php
2
3 namespace App\Providers;
4
5 use Illuminate\Support\Facades\Blade;
6 use Illuminate\Support\ServiceProvider;
7
8 class AppServiceProvider extends ServiceProvider
9 {
10 /**
11 * Bootstrap any application services.
12 *
13 * @return void
14 */
15 public function boot()
16 {
17 Blade::withoutDoubleEncoding();
18 }
19 }
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
1 @unless (Auth::check())
2 You are not signed in.
3 @endunless
1 @isset($records)
2 // $records is defined and is not null...
3 @endisset
4
5 @empty($records)
6 // $records is "empty"...
7 @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
5 @guest
6 // The user is not authenticated...
7 @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
5 @guest('admin')
6 // The user is not authenticated...
7 @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
6 <div class="clearfix"></div>
7 @endif
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
6 @case(2)
7 Second case...
8 @break
9
10 @default
11 Default case...
12 @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:
{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:
You may also include the condition with the directive declaration in
one line:
If you are in a nested loop, you may access the parent loop's $loop
variable via the parent property:
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:
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
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:
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:
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:
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.
1 use Illuminate\Support\Facades\Blade;
2
3 /**
4 * Bootstrap your package's services.
5 */
6 public function boot()
7 {
8 Blade::component('package-alert',
AlertComponent::class);
9 }
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
3 <x-user-profile/>
1 <x-inputs.button/>
1 <?php
2
3 namespace App\View\Components;
4
5 use Illuminate\View\Component;
6
7 class Alert extends Component
8 {
9 /**
10 * The alert type.
11 *
12 * @var string
13 */
14 public $type;
15
16 /**
17 * The alert message.
18 *
19 * @var string
20 */
21 public $message;
22
23 /**
24 * Create the component instance.
25 *
26 * @param string $type
27 * @param string $message
28 * @return void
29 */
30 public function __construct($type, $message)
31 {
32 $this->type = $type;
33 $this->message = $message;
34 }
35
36 /**
37 * Get the view / contents that represent the
component.
38 *
39 * @return \Illuminate\View\View|string
40 */
41 public function render()
42 {
43 return view('components.alert');
44 }
45 }
When your component is rendered, you may display the contents of
your component's public variables by echoing the variables by name:
Casing
1 /**
2 * Create the component instance.
3 *
4 * @param string $alertType
5 * @param string $message
6 * @return void
7 */
8 public function __construct($alertType)
9 {
10 $this->alertType = $alertType;
11 }
Component Methods
1 /**
2 * Get the size.
3 *
4 * @return string
5 */
6 public function size()
7 {
8 return 'Large';
9 }
1 {{ $size }}
Additional Dependencies
1 use App\AlertCreator
2
3 /**
4 * Create the component instance.
5 *
6 * @param \App\AlertCreator $creator
7 * @param string $type
8 * @param string $message
9 * @return void
10 */
11 public function __construct(AlertCreator $creator,
$type, $message)
12 {
13 $this->creator = $creator;
14 $this->type = $type;
15 $this->message = $message;
16 }
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:
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:
The final, rendered HTML of the component will appear like the
following:
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 <x-alert>
2 <strong>Whoops!</strong> Something went wrong!
3 </x-alert>
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
6 <strong>Whoops!</strong> Something went wrong!
7 </x-alert>
To create a component that renders an inline view, you may use the
inline option when executing the make:component command:
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/>
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
4 <form>
5 <!-- Form Contents -->
6 </form>
7 </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:
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:
To include the first view that exists from a given array of views, you
may use the includeFirst directive:
Aliasing Includes
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
3 Blade::include('includes.input', 'input');
Once the include has been aliased, you may render it using the alias
name as the Blade directive:
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.
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
1 <head>
2 <!-- Head Contents -->
3
4 @stack('scripts')
5 </head>
1 @push('scripts')
2 This will be second...
3 @endpush
4
5 // Later...
6
7 @prepend('scripts')
8 This will be first...
9 @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
3 <div>
4 Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
5 </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.
1 <?php
2
3 namespace App\Providers;
4
5 use Illuminate\Support\Facades\Blade;
6 use Illuminate\Support\ServiceProvider;
7
8 class AppServiceProvider extends ServiceProvider
9 {
10 /**
11 * Register any application services.
12 *
13 * @return void
14 */
15 public function register()
16 {
17 //
18 }
19
20 /**
21 * Bootstrap any application services.
22 *
23 * @return void
24 */
25 public function boot()
26 {
27 Blade::directive('datetime', function
($expression) {
28 return "<?php echo ($expression)-
>format('m/d/Y H:i'); ?>";
29 });
30 }
31 }
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:
{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 environment. We may do this in the boot method of our
AppServiceProvider :
1 use Illuminate\Support\Facades\Blade;
2
3 /**
4 * Bootstrap any application services.
5 *
6 * @return void
7 */
8 public function boot()
9 {
10 Blade::if('env', function ($environment) {
11 return app()->environment($environment);
12 });
13 }
Once the custom conditional has been defined, we can easily use it on
our templates:
1 @env('local')
2 // The application is in the local environment...
3 @elseenv('testing')
4 // The application is in the testing
environment...
5 @else
6 // The application is not in the local or testing
environment...
7 @endenv
8
9 @unlessenv('production')
10 // The application is not in the production
environment...
11 @endenv