![]() |
VOOZH | about |
WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 13.x.
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.
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<!--Storedinresources/views/layouts/app.blade.php--> 2 3<html> 4<head> 5<title>AppName-@yield('title')</title> 6</head> 7<body> 8@section('sidebar') 9Thisisthemastersidebar.10@show11 12<divclass="container">13@yield('content')14</div>15</body>16</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.
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<!--Storedinresources/views/child.blade.php--> 2 3@extends('layouts.app') 4 5@section('title','Page Title') 6 7@section('sidebar') 8@@parent 9 10<p>Thisisappendedtothemastersidebar.</p>11@endsection12 13@section('content')14<p>Thisismybodycontent.</p>15@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.
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:
1Route::get('blade', function() {2returnview('child');3});
Components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. First, let's imagine a reusable "alert" component we would like to reuse throughout our application:
1<!--/resources/views/alert.blade.php-->2 3<divclass="alert alert-danger">4 {{ $slot }}5</div>
The {{ $slot }} variable will contain the content we wish to inject into the component. Now, to construct this component, we can use the @component Blade directive:
1@component('alert')2<strong>Whoops!</strong>Somethingwentwrong!3@endcomponent
To instruct Laravel to load the first view that exists from a given array of possible views for the component, you may use the componentFirst directive:
1@componentFirst(['custom.alert','alert'])2<strong>Whoops!</strong>Somethingwentwrong!3@endcomponent
Sometimes it is helpful to define multiple slots for a component. Let's modify our alert component to allow for the injection of a "title". Named slots may be displayed by "echoing" the variable that matches their name:
1<!--/resources/views/alert.blade.php-->2 3<divclass="alert alert-danger">4<divclass="alert-title">{{ $title }}</div>5 6 {{ $slot }}7</div>
Now, we can inject content into the named slot using the @slot directive. Any content not within a @slot directive will be passed to the component in the $slot variable:
1@component('alert')2@slot('title')3Forbidden4@endslot5 6Youarenotallowedtoaccessthisresource!7@endcomponent
Sometimes you may need to pass additional data to a component. For this reason, you can pass an array of data as the second argument to the @component directive. All of the data will be made available to the component template as variables:
1@component('alert',['foo'=>'bar'])2...3@endcomponent
If your Blade components are stored in a sub-directory, you may wish to alias them for easier access. For example, imagine a Blade component that is stored at resources/views/components/alert.blade.php. You may use the component method to alias the component from components.alert to alert. Typically, this should be done in the boot method of your AppServiceProvider:
1use Illuminate\Support\Facades\Blade;2 3Blade::component('components.alert', 'alert');
Once the component has been aliased, you may render it using a directive:
1@alert(['type'=>'danger'])2Youarenotallowedtoaccessthisresource!3@endalert
You may omit the component parameters if it has no additional slots:
1@alert2Youarenotallowedtoaccessthisresource!3@endalert
You may display data passed to your Blade views by wrapping the variable in curly braces. For example, given the following route:
1Route::get('greeting', function() {2returnview('welcome',['name'=>'Samantha']);3});
You may display the contents of the name variable like so:
1Hello, {{ $name }}.
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:
1ThecurrentUNIXtimestampis {{ time() }}.
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:
1Hello, {!!$name!!}.
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.
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>2var app =<?phpechojson_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>2varapp=@json($array);3 4varapp=@json($array, JSON_PRETTY_PRINT);5</script>
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.
The @json directive is also useful for seeding Vue components or data-* attributes:
1<example-component :some-prop='@json($array)'></example-component>
Using @json in element attributes requires that it be surrounded by single quotes.
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 3namespace App\Providers; 4 5use Illuminate\Support\Facades\Blade; 6use Illuminate\Support\ServiceProvider; 7 8classAppServiceProviderextendsServiceProvider 9{10/**11 * Bootstrap any application services.12 *13 * @returnvoid14*/15publicfunctionboot()16 {17Blade::withoutDoubleEncoding();18 }19}
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 3Hello, @{{ 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.
@verbatim DirectiveIf 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@verbatim2<divclass="container">3Hello, {{ name }}.4</div>5@endverbatim
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.
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)2Ihaveonerecord!3@elseif (count($records) >1)4Ihavemultiplerecords!5@else6Idon't have any records!7@endif
For convenience, Blade also provides an @unless directive:
1@unless (Auth::check())2Youarenotsignedin.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@endisset4 5@empty($records)6// $records is "empty"...7@endempty
The @auth and @guest directives may be used to quickly determine if the current user is authenticated or is a guest:
1@auth2// The user is authenticated...3@endauth4 5@guest6// 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@endauth4 5@guest('admin')6// The user is not authenticated...7@endguest
You may check if a section has content using the @hasSection directive:
1@hasSection('navigation')2<divclass="pull-right">3@yield('navigation')4</div>5 6<divclass="clearfix"></div>7@endif
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 @default11 Default case...12@endswitch
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++) 2Thecurrentvalueis {{ $i }} 3@endfor 4 5@foreach ($usersas$user) 6<p>Thisisuser {{ $user->id }}</p> 7@endforeach 8 9@forelse ($usersas$user)10<li>{{ $user->name }}</li>11@empty12<p>Nousers</p>13@endforelse14 15@while (true)16<p>I'm looping forever.</p>17@endwhile
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 ($usersas$user) 2@if ($user->type==1) 3@continue 4@endif 5 6<li>{{ $user->name }}</li> 7 8@if ($user->number==5) 9@break10@endif11@endforeach
You may also include the condition with the directive declaration in one line:
1@foreach ($usersas$user)2@continue($user->type==1)3 4<li>{{ $user->name }}</li>5 6@break($user->number==5)7@endforeach
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 ($usersas$user) 2@if ($loop->first) 3Thisisthefirstiteration. 4@endif 5 6@if ($loop->last) 7Thisisthelastiteration. 8@endif 9 10<p>Thisisuser {{ $user->id }}</p>11@endforeach
If you are in a nested loop, you may access the parent loop's $loop variable via the parent property:
1@foreach ($usersas$user)2@foreach ($user->postsas$post)3@if ($loop->parent->first)4Thisisfirstiterationoftheparentloop.5@endif6@endforeach7@endforeach
The $loop variable also contains a variety of other useful properties:
| Property | Description |
|---|---|
$loop->index |
The index of the current loop iteration (starts at 0). |
$loop->iteration |
The current loop iteration (starts at 1). |
$loop->remaining |
The iterations remaining in the loop. |
$loop->count |
The total number of items in the array being iterated. |
$loop->first |
Whether this is the first iteration through the loop. |
$loop->last |
Whether this is the last iteration through the loop. |
$loop->even |
Whether this is an even iteration through the loop. |
$loop->odd |
Whether this is an odd iteration through the loop. |
$loop->depth |
The nesting level of the current loop. |
$loop->parent |
When in a nested loop, the parent's loop variable. |
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{{--ThiscommentwillnotbepresentintherenderedHTML--}}
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@php2//3@endphp
While Blade provides this feature, using it frequently may be a signal that you have too much logic embedded within your template.
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<formmethod="POST"action="/profile">2@csrf3 4...5</form>
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<formaction="/foo/bar"method="POST">2@method('PUT')3 4...5</form>
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 3<labelfor="title">PostTitle</label>4 5<inputid="title"type="text"class="@error('title') is-invalid @enderror">6 7@error('title')8<divclass="alert alert-danger">{{ $message }}</div>9@enderror
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<!--FormContents-->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:
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 depending on a given boolean condition, you may use the @includeWhen directive:
1@includeWhen($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'])
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.
If your Blade includes are stored in a sub-directory, 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<inputtype="{{ $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:
1use Illuminate\Support\Facades\Blade;2 3Blade::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'])
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')
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.
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<scriptsrc="/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<!--HeadContents-->3 4@stack('scripts')5</head>
If you would like to prepend content onto the beginning of a stack, you should use the @prepend directive:
1@push('scripts')2Thiswillbesecond...3@endpush4 5// Later...6 7@prepend('scripts')8Thiswillbefirst...9@endprepend
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>4MonthlyRevenue: {{ $metrics->monthlyRevenue() }}.5</div>
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 3namespace App\Providers; 4 5use Illuminate\Support\Facades\Blade; 6use Illuminate\Support\ServiceProvider; 7 8classAppServiceProviderextendsServiceProvider 9{10/**11 * Register bindings in the container.12 *13 * @returnvoid14*/15publicfunctionregister()16 {17//18 }19 20/**21 * Bootstrap any application services.22 *23 * @returnvoid24*/25publicfunctionboot()26 {27Blade::directive('datetime', function($expression) {28return"<?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:
1<?phpecho($var)->format('m/d/Y H:i'); ?>
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.
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:
1use Illuminate\Support\Facades\Blade; 2 3/** 4 * Bootstrap any application services. 5 * 6 * @returnvoid 7*/ 8publicfunctionboot() 9{10Blade::if('env', function($environment) {11returnapp()->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@else6// The application is not in the local or testing environment...7@endenv