![]()
WARNING You're browsing the documentation for an upcoming version of Laravel. The documentation and features of this release are subject to change.
Blade Templates
- Introduction
- Displaying Data
- Blade Directives
- Components
- Building Layouts
- Forms
- Stacks
- Service Injection
- Extending Blade
Introduction
Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade template files use the
.blade.phpfile extension and are typically stored in theresources/viewsdirectory.Blade views may be returned from routes or controller using the global
viewhelper. Of course, as mentioned in the documentation on views, data may be passed to the Blade view using theviewhelper's second argument:Route::get('/', function () { return view('greeting', ['name' => 'Finn']); });{tip} Before digging deeper into Blade, make sure to read the Laravel view documentation.
Displaying Data
You may display data that is passed to your Blade views by wrapping the variable in curly braces. For example, given the following route:
Route::get('/', function () { return view('welcome', ['name' => 'Samantha']); });You may display the contents of the
namevariable like so:Hello, {{ $name }}.{tip} Blade's
{{ }}echo statements are automatically sent through PHP'shtmlspecialcharsfunction 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:
The current UNIX timestamp is {{ time() }}.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:
<script> var app = <?php echo json_encode($array); ?>; </script>However, instead of manually calling
json_encode, you may use the@jsonBlade directive. The@jsondirective accepts the same arguments as PHP'sjson_encodefunction. By default, the@jsondirective calls thejson_encodefunction with theJSON_HEX_TAG,JSON_HEX_APOS,JSON_HEX_AMP, andJSON_HEX_QUOTflags:<script> var app = @json($array); var app = @json($array, JSON_PRETTY_PRINT); </script>{note} You should only use the
@jsondirective 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
ehelper) will double encode HTML entities. If you would like to disable double encoding, call theBlade::withoutDoubleEncodingmethod from thebootmethod of yourAppServiceProvider:<?php namespace App\Providers; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Blade::withoutDoubleEncoding(); } }Displaying Unescaped Data
By default, Blade
{{ }}statements are automatically sent through PHP'shtmlspecialcharsfunction to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:Hello, {!! $name !!}.{note} Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.
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:<h1>Laravel</h1> 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 be rendered by your JavaScript framework.The
@symbol may also be used to escape Blade directives:{{-- Blade template --}} @@json() <!-- HTML output --> @json()The
@verbatimDirectiveIf you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the
@verbatimdirective so that you do not have to prefix each Blade echo statement with an@symbol:@verbatim <div class="container"> Hello, {{ name }}. </div> @endverbatimBlade Directives
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
ifstatements using the@if,@elseif,@else, and@endifdirectives. These directives function identically to their PHP counterparts:@if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endifFor convenience, Blade also provides an
@unlessdirective:@unless (Auth::check()) You are not signed in. @endunlessIn addition to the conditional directives already discussed, the
@issetand@emptydirectives may be used as convenient shortcuts for their respective PHP functions:@isset($records) // $records is defined and is not null... @endisset @empty($records) // $records is "empty"... @endemptyAuthentication Directives
The
@authand@guestdirectives may be used to quickly determine if the current user is authenticated or is a guest:@auth // The user is authenticated... @endauth @guest // The user is not authenticated... @endguestIf needed, you may specify the authentication guard that should be checked when using the
@authand@guestdirectives:@auth('admin') // The user is authenticated... @endauth @guest('admin') // The user is not authenticated... @endguestEnvironment Directives
You may check if the application is running in the production environment using the
@productiondirective:@production // Production specific content... @endproductionOr, you may determine if the application is running in a specific environment using the
@envdirective:@env('staging') // The application is running in "staging"... @endenv @env(['staging', 'production']) // The application is running in "staging" or "production"... @endenvSection Directives
You may determine if a template inheritance section has content using the
@hasSectiondirective:@hasSection('navigation') <div class="pull-right"> @yield('navigation') </div> <div class="clearfix"></div> @endifYou may use the
sectionMissingdirective to determine if a section does not have content:@sectionMissing('navigation') <div class="pull-right"> @include('default-navigation') </div> @endifSwitch Statements
Switch statements can be constructed using the
@switch,@case,@break,@defaultand@endswitchdirectives:@switch($i) @case(1) First case... @break @case(2) Second case... @break @default Default case... @endswitchLoops
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:
@for ($i = 0; $i < 10; $i++) The current value is {{ $i }} @endfor @foreach ($users as $user) <p>This is user {{ $user->id }}</p> @endforeach @forelse ($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse @while (true) <p>I'm looping forever.</p> @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 using the
@continueand@breakdirectives:@foreach ($users as $user) @if ($user->type == 1) @continue @endif <li>{{ $user->name }}</li> @if ($user->number == 5) @break @endif @endforeachYou may also include the continuation or break condition within the directive declaration:
@foreach ($users as $user) @continue($user->type == 1) <li>{{ $user->name }}</li> @break($user->number == 5) @endforeachThe Loop Variable
When looping, a
$loopvariable 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:@foreach ($users as $user) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif <p>This is user {{ $user->id }}</p> @endforeachIf you are in a nested loop, you may access the parent loop's
$loopvariable via theparentproperty:@foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->parent->first) This is the first iteration of the parent loop. @endif @endforeach @endforeachThe
$loopvariable also contains a variety of other useful properties:
Property Description $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:
{{-- This comment will not be present in the rendered HTML --}}Including Subviews
{tip} While you're free to use the
@includedirective, Blade components provide similar functionality and offer several benefits over the@includedirective such as data and attribute binding.Blade's
@includedirective 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:<div> @include('shared.errors') <form> <!-- Form Contents --> </form> </div>Even though the included view will inherit all data available in the parent view, you may also pass an array of additional data that should be made available to the included view:
@include('view.name', ['status' => 'complete'])If you attempt to
@includea 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@includeIfdirective:@includeIf('view.name', ['status' => 'complete'])If you would like to
@includea view if a given boolean expression evaluates totrueorfalse, you may use the@includeWhenand@includeUnlessdirectives:@includeWhen($boolean, 'view.name', ['status' => 'complete']) @includeUnless($boolean, 'view.name', ['status' => 'complete'])To include the first view that exists from a given array of views, you may use the
includeFirstdirective:@includeFirst(['custom.admin', 'admin'], ['status' => 'complete']){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.Rendering Views For Collections
You may combine loops and includes into one line with Blade's
@eachdirective:@each('view.name', $jobs, 'job')The
@eachdirective's first argument is the view 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 ofjobs, typically you will want to access each job as ajobvariable within the view. The array key for the current iteration will be available as thekeyvariable within the view.You may also pass a fourth argument to the
@eachdirective. This argument determines the view that will be rendered if the given array is empty.@each('view.name', $jobs, 'job', 'view.empty'){note} Views rendered via
@eachdo not inherit the variables from the parent view. If the child view requires these variables, you should use the@foreachand@includedirectives instead.The
@onceDirectiveThe
@oncedirective allows you to define a portion of the template that will only be evaluated 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 first time the component is rendered:@once @push('scripts') <script> // Your custom JavaScript... </script> @endpush @endonceBuilding Layouts
Layouts Using Components
Most web applications maintain the same general layout across various pages. It would be incredibly cumbersome and hard to maintain our application if we had to repeat the entire layout HTML in every view we create. Thankfully, it's convenient to define this layout as a single Blade component and then use it throughout our application.
Defining The Layout Component
For example, imagine we are building a "todo" list application. We might define a
layoutcomponent that looks like the following:<!-- resources/views/components/layout.blade.php --> <html> <head> <title>{{ $title ?? 'Todo Manager' }}</title> </head> <body> <h1>Todos</h1> <hr/> {{ $slot }} </body> </html>Applying The Layout Component
Once the
layoutcomponent has been defined, we may create a Blade view that utilizes the component. In this example, we will define a simple view that displays our task list:<!-- resources/views/tasks.blade.php --> <x-layout> @foreach ($tasks as $task) {{ $task }} @endforeach </x-layout>Remember, content that is injected into a component will be supplied to the default
$slotvariable within ourlayoutcomponent. As you may have noticed, ourlayoutalso respects a$titleslot if one is provided; otherwise, a default title is shown. We may inject a custom title from our task list view using the standard slot syntax discussed in the component documentation:<!-- resources/views/tasks.blade.php --> <x-layout> <x-slot name="title"> Custom Title </x-slot> @foreach ($tasks as $task) {{ $task }} @endforeach </x-layout>Now that we have defined our layout and task list views, we just need to return the
taskview from a route:use App\Models\Task; Route::get('/tasks', function () { return view('tasks', ['tasks' => Task::all()]); });Layouts Using Template Inheritance
Defining A Layout
Layouts may also be created via "template inheritance". This was the primary way of building applications prior to the introduction of components.
To get started, let's take a look at a simple example. First, we will examine a 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:
<!-- resources/views/layouts/app.blade.php --> <html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @show <div class="container"> @yield('content') </div> </body> </html>As you can see, this file contains typical HTML mark-up. However, take note of the
@sectionand@yielddirectives. The@sectiondirective, as the name implies, defines a section of content, while the@yielddirective 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
@extendsBlade 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@sectiondirectives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using@yield:<!-- resources/views/child.blade.php --> @extends('layouts.app') @section('title', 'Page Title') @section('sidebar') @parent <p>This is appended to the master sidebar.</p> @endsection @section('content') <p>This is my body content.</p> @endsectionIn this example, the
sidebarsection is utilizing the@parentdirective to append (rather than overwriting) content to the layout's sidebar. The@parentdirective will be replaced by the content of the layout when the view is rendered.{tip} Contrary to the previous example, this
sidebarsection ends with@endsectioninstead of@show. The@endsectiondirective will only define a section while@showwill define and immediately yield the section.The
@yielddirective also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined:@yield('content', 'Default content')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
@csrfBlade directive to generate the token field:<form method="POST" action="/profile"> @csrf ... </form>Method Field
Since HTML forms can't make
PUT,PATCH, orDELETErequests, you will need to add a hidden_methodfield to spoof these HTTP verbs. The@methodBlade directive can create this field for you:<form action="/foo/bar" method="POST"> @method('PUT') ... </form>Validation Errors
The
@errordirective may be used to quickly check if validation error messages exist for a given attribute. Within an@errordirective, you may echo the$messagevariable to display the error message:<!-- /resources/views/post/create.blade.php --> <label for="title">Post Title</label> <input id="title" type="text" class="@error('title') is-invalid @enderror"> @error('title') <div class="alert alert-danger">{{ $message }}</div> @enderrorYou may pass the name of a specific error bag as the second parameter to the
@errordirective to retrieve validation error messages on pages containing multiple forms:<!-- /resources/views/auth.blade.php --> <label for="email">Email address</label> <input id="email" type="email" class="@error('email', 'login') is-invalid @enderror"> @error('email', 'login') <div class="alert alert-danger">{{ $message }}</div> @enderrorRaw PHP
In some situations, it's useful to embed PHP code into your views. You can use the Blade
@phpdirective to execute a block of plain PHP within your template:@php $counter = 1; @endphpComponents
Components and slots provide similar benefits to sections, layouts, and includes; 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:componentArtisan command. To illustrate how to use components, we will create a simpleAlertcomponent. Themake:componentcommand will place the component in theApp\View\Componentsdirectory:php artisan make:component AlertThe
make:componentcommand will also create a view template for the component. The view will be placed in theresources/views/componentsdirectory. When writing components for your own application, components are automatically discovered within theapp/View/Componentsdirectory andresources/views/componentsdirectory, so no further component registration is typically required.You may also create components within subdirectories:
php artisan make:component Forms/InputThe command above will create an
Inputcomponent in theApp\View\Components\Formsdirectory and the view will be placed in theresources/views/components/formsdirectory.Manually Registering Package Components
When writing components for your own application, components are automatically discovered within the
app/View/Componentsdirectory andresources/views/componentsdirectory.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
bootmethod of your package's service provider:use Illuminate\Support\Facades\Blade; /** * Bootstrap your package's services. */ public function boot() { Blade::component('package-alert', Alert::class); }Once your component has been registered, it may be rendered using its tag alias:
<x-package-alert/>Alternatively, you may use the
componentNamespacemethod to autoload component classes by convention. For example, aNightshadepackage might haveCalendarandColorPickercomponents that reside within thePackage\Views\Componentsnamespace:use Illuminate\Support\Facades\Blade; /** * Bootstrap your package's services. * * @return void */ public function boot() { Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); }This will allow the usage of package components by their vendor namespace using the
package-name::syntax:<x-nightshade::calendar /> <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.
Rendering 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:<x-alert/> <x-user-profile/>If the component class is nested deeper within the
App\View\Componentsdirectory, you may use the.character to indicate directory nesting. For example, if we assume a component is located atApp\View\Components\Inputs\Button.php, we may render it like so:<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 attribute strings. PHP expressions and variables should be passed to the component via attributes that use the
:character as a prefix:<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
rendermethod:<?php namespace App\View\Components; use Illuminate\View\Component; class Alert extends Component { /** * The alert type. * * @var string */ public $type; /** * The alert message. * * @var string */ public $message; /** * Create the component instance. * * @param string $type * @param string $message * @return void */ public function __construct($type, $message) { $this->type = $type; $this->message = $message; } /** * Get the view / contents that represent the component. * * @return \Illuminate\View\View|\Closure|string */ public function render() { return view('components.alert'); } }When your component is rendered, you may display the contents of your component's public variables by echoing the variables by name:
<div class="alert alert-{{ $type }}"> {{ $message }} </div>Casing
Component constructor arguments should be specified using
camelCase, whilekebab-caseshould be used when referencing the argument names in your HTML attributes. For example, given the following component constructor:/** * Create the component instance. * * @param string $alertType * @return void */ public function __construct($alertType) { $this->alertType = $alertType; }The
$alertTypeargument may be provided to the component like so:<x-alert alert-type="danger" />Escaping Attribute Rendering
Since some JavaScript frameworks such as Alpine.js also use colon-prefixed attributes, you may use a double colon (
::) prefix to inform Blade that the attribute is not a PHP expression. For example, given the following component:<x-button ::class="{ danger: isDeleting }"> Submit </x-button>The following HTML will be rendered by Blade:
<button :class="{ danger: isDeleting }"> Submit </button>Component Methods
In addition to public variables being available to your component template, any public methods on the component may be invoked. For example, imagine a component that has an
isSelectedmethod:/** * Determine if the given option is the currently selected option. * * @param string $option * @return bool */ public function isSelected($option) { return $option === $this->selected; }You may execute this method from your component template by invoking the variable matching the name of the method:
<option {{ $isSelected($value) ? 'selected="selected"' : '' }} value="{{ $value }}"> {{ $label }} </option>Accessing Attributes & Slots Within Component Classes
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
rendermethod. The closure will receive a$dataarray as its only argument. This array will contain several elements that provide information about the component:/** * Get the view / contents that represent the component. * * @return \Illuminate\View\View|\Closure|string */ public function render() { return function (array $data) { // $data['componentName']; // $data['attributes']; // $data['slot']; return '<div>Components content</div>'; }; }The
componentNameis equal to the name used in the HTML tag after thex-prefix. So<x-alert />'scomponentNamewill bealert. Theattributeselement will contain all of the attributes that were present on the HTML tag. Theslotelement is anIlluminate\Support\HtmlStringinstance with the contents of the component's slot.The closure should return a string. If the returned string corresponds to an existing view, that view will be rendered; otherwise, the returned string will be evaluated as an inline Blade view.
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:
use App\Services\AlertCreator /** * Create the component instance. * * @param \App\Services\AlertCreator $creator * @param string $type * @param string $message * @return void */ public function __construct(AlertCreator $creator, $type, $message) { $this->creator = $creator; $this->type = $type; $this->message = $message; }Component 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 analertcomponent like so:<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
$attributesvariable. All of the attributes may be rendered within the component by echoing this variable:<div {{ $attributes }}> <!-- Component content --> </div>{note} Using directives such as
@envwithin component tags is not supported at this time. For example,<x-alert :live="@env('production')"/>will not be compiled.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
mergemethod. This method is particularly useful for defining a set of default CSS classes that should always be applied to a component:<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> {{ $message }} </div>If we assume this component is utilized like so:
<x-alert type="error" :message="$message" class="mb-4"/>The final, rendered HTML of the component will appear like the following:
<div class="alert alert-error mb-4"> <!-- Contents of the $message variable --> </div>Non-Class Attribute Merging
When merging attributes that are not
classattributes, the values provided to themergemethod will be considered the "default" values of the attribute. However, unlike theclassattribute, these attributes will not be merged with injected attribute values. Instead, they will be overwritten. For example, abuttoncomponent's implementation may look like the following:<button {{ $attributes->merge(['type' => 'button']) }}> {{ $slot }} </button>To render the button component with a custom
type, it may be specified when consuming the component. If no type is specified, thebuttontype will be used:<x-button type="submit"> Submit </x-button>The rendered HTML of the
buttoncomponent in this example would be:<button type="submit"> Submit </button>If you would like an attribute other than
classto have its default value and injected values joined together, you may use theprependsmethod. In this example, thedata-controllerattribute will always begin withprofile-controllerand any additional injecteddata-controllervalues will be placed after this default value:<div {{ $attributes->merge(['data-controller' => $attributes->prepends('profile-controller')]) }}> {{ $slot }} </div>Retrieving & Filtering Attributes
You may filter attributes using the
filtermethod. This method accepts a closure which should returntrueif you wish to retain the attribute in the attribute bag:{{ $attributes->filter(fn ($value, $key) => $key == 'foo') }}For convenience, you may use the
whereStartsWithmethod to retrieve all attributes whose keys begin with a given string:{{ $attributes->whereStartsWith('wire:model') }}Using the
firstmethod, you may render the first attribute in a given attribute bag:{{ $attributes->whereStartsWith('wire:model')->first() }}If you would like to check if an attribute is present on the component, you may use the
hasmethod. This method accepts the attribute name as its only argument and returns a boolean indicating whether or not the attribute is present:@if ($attributes->has('class')) <div>Class attribute is present</div> @endifYou may retrieve a specific attribute's value using the
getmethod:{{ $attributes->get('class') }}Slots
You will often need to pass additional content to your component via "slots". Component slots are rendered by echoing the
$slotvariable. To explore this concept, let's imagine that analertcomponent has the following markup:<!-- /resources/views/components/alert.blade.php --> <div class="alert alert-danger"> {{ $slot }} </div>We may pass content to the
slotby injecting content into the component:<x-alert> <strong>Whoops!</strong> Something went wrong! </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" slot:
<!-- /resources/views/components/alert.blade.php --> <span class="alert-title">{{ $title }}</span> <div class="alert alert-danger"> {{ $slot }} </div>You may define the content of the named slot using the
x-slottag. Any content not within an explicitx-slottag will be passed to the component in the$slotvariable:<x-alert> <x-slot name="title"> Server Error </x-slot> <strong>Whoops!</strong> Something went wrong! </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
$componentvariable. In this example, we will assume that thex-alertcomponent has a publicformatAlertmethod defined on its component class:<x-alert> <x-slot name="title"> {{ $component->formatAlert('Server Error') }} </x-slot> <strong>Whoops!</strong> Something went wrong! </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
rendermethod:/** * Get the view / contents that represent the component. * * @return \Illuminate\View\View|\Closure|string */ public function render() { return <<<'blade' <div class="alert alert-danger"> {{ $slot }} </div> blade; }Generating Inline View Components
To create a component that renders an inline view, you may use the
inlineoption when executing themake:componentcommand:php artisan make:component Alert --inlineAnonymous 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/componentsdirectory. For example, assuming you have defined a component atresources/views/components/alert.blade.php, you may simply render it like so:<x-alert/>You may use the
.character to indicate if a component is nested deeper inside thecomponentsdirectory. For example, assuming the component is defined atresources/views/components/inputs/button.blade.php, you may render it like so:<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
@propsdirective 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:<!-- /resources/views/components/alert.blade.php --> @props(['type' => 'info', 'message']) <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> {{ $message }} </div>Given the component definition above, we may render the component like so:
<x-alert type="error" :message="$message" class="mb-4"/>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-componentcomponent to render the component based on a runtime value or variable:<x-dynamic-component :component="$componentName" class="mt-4" />Manually Registering Components
{note} The following documentation on manually registering components is primarily applicable to those who are writing Laravel packages that include view components. If you are not writing a package, this portion of the component documentation may not be relevant to you.
When writing components for your own application, components are automatically discovered within the
app/View/Componentsdirectory andresources/views/componentsdirectory.However, if you are building a package that utilizes Blade components or placing components in non-conventional directories, you will need to manually register your component class and its HTML tag alias so that Laravel knows where to find the component. You should typically register your components in the
bootmethod of your package's service provider:use Illuminate\Support\Facades\Blade; use VendorPackage\View\Components\AlertComponent; /** * Bootstrap your package's services. * * @return void */ public function boot() { Blade::component('package-alert', AlertComponent::class); }Once your component has been registered, it may be rendered using its tag alias:
<x-package-alert/>Autoloading Package Components
Alternatively, you may use the
componentNamespacemethod to autoload component classes by convention. For example, aNightshadepackage might haveCalendarandColorPickercomponents that reside within thePackage\Views\Componentsnamespace:use Illuminate\Support\Facades\Blade; /** * Bootstrap your package's services. * * @return void */ public function boot() { Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); }This will allow the usage of package components by their vendor namespace using the
package-name::syntax:<x-nightshade::calendar /> <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.
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:
@push('scripts') <script src="/example.js"></script> @endpushYou may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the
@stackdirective:<head> <!-- Head Contents --> @stack('scripts') </head>If you would like to prepend content onto the beginning of a stack, you should use the
@prependdirective:@push('scripts') This will be second... @endpush // Later... @prepend('scripts') This will be first... @endprependService Injection
The
@injectdirective may be used to retrieve a service from the Laravel service container. The first argument passed to@injectis 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:@inject('metrics', 'App\Services\MetricsService') <div> Monthly Revenue: {{ $metrics->monthlyRevenue() }}. </div>Extending Blade
Blade allows you to define your own custom directives using the
directivemethod. 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 ofDateTime:<?php namespace App\Providers; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { Blade::directive('datetime', function ($expression) { return "<?php echo ($expression)->format('m/d/Y H:i'); ?>"; }); } }As you can see, we will chain the
formatmethod onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be:<?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:clearArtisan 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::ifmethod which allows you to quickly define custom conditional directives using closures. For example, let's define a custom conditional that checks the configured default "disk" for the application. We may do this in thebootmethod of ourAppServiceProvider:use Illuminate\Support\Facades\Blade; /** * Bootstrap any application services. * * @return void */ public function boot() { Blade::if('disk', function ($value) { return config('filesystems.default') === $value; }); }Once the custom conditional has been defined, you can use it within your templates:
@disk('local') <!-- The application is using the local disk... --> @elsedisk('s3') <!-- The application is using the s3 disk... --> @else <!-- The application is using some other disk... --> @enddisk @unlessdisk('local') <!-- The application is not using the local disk... --> @enddisk