Blade Templates
Blade Templates
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.php file extension and are typically stored in the resources/views directory.
Blade views may be returned from routes or controllers using the global view helper. Of course, as mentioned in the documentation on views, data may be passed to the Blade view using the view helper’s second argument:
Route::get('/', function () {
return view('greeting', ['name' => 'Finn']);
});
Route::get('/', function () {
return view('greeting', ['name' => 'Finn']);
});
Supercharging Blade With Livewire
Want to take your Blade templates to the next level and build dynamic interfaces with ease? Check out Laravel Livewire. Livewire allows you to write Blade components that are augmented with dynamic functionality that would typically only be possible via frontend frameworks like React or Vue, providing a great approach to building modern, reactive frontends without the complexities, client-side rendering, or build steps of many JavaScript frameworks.
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']);
});
Route::get('/', function () {
return view('welcome', ['name' => 'Samantha']);
});
You may display the contents of the name variable like so:
Hello, {{ $name }}.
Hello, {{ $name }}.
Blade’s {{ }} echo 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:
The current UNIX timestamp is {{ time() }}.
The current UNIX timestamp is {{ time() }}.
HTML Entity Encoding
By default, Blade (and the Laravel e function) 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:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::withoutDoubleEncoding();
}
}
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::withoutDoubleEncoding();
}
}
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:
Hello, {!! $name !!}.
Hello, {!! $name !!}.
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 and 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 }}.
<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 --}}
@@if()
<!-- HTML output -->
@if()
{{-- Blade template --}}
@@if()
<!-- HTML output -->
@if()
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>
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the Illuminate\Support\Js::from method directive. The from method accepts the same arguments as PHP’s json_encode function; however, it will ensure that the resulting JSON is properly escaped for inclusion within HTML quotes. The from method will return a string JSON.parse JavaScript statement that will convert the given object or array into a valid JavaScript object:
<script>
var app = {{ Illuminate\Support\Js::from($array) }};
</script>
<script>
var app = {{ Illuminate\Support\Js::from($array) }};
</script>
The latest versions of the Laravel application skeleton include a Js facade, which provides convenient access to this functionality within your Blade templates:
<script>
var app = {{ Js::from($array) }};
</script>
<script>
var app = {{ Js::from($array) }};
</script>
You should only use the Js::from method 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 @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:
@verbatim
<div class="container">
Hello, {{ name }}.
</div>
@endverbatim
@verbatim
<div class="container">
Hello, {{ name }}.
</div>
@endverbatim
Blade 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 if statements using the @if, @elseif, @else, and @endif directives. 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!
@endif
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif
For convenience, Blade also provides an @unless directive:
@unless (Auth::check())
You are not signed in.
@endunless
@unless (Auth::check())
You are not signed in.
@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:
@isset($records)
// $records is defined and is not null...
@endisset
@empty($records)
// $records is "empty"...
@endempty
@isset($records)
// $records is defined and is not null...
@endisset
@empty($records)
// $records is "empty"...
@endempty
Authentication Directives
The @auth and @guest directives 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...
@endguest
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
If needed, you may specify the authentication guard that should be checked when using the @auth and @guest directives:
@auth('admin')
// The user is authenticated...
@endauth
@guest('admin')
// The user is not authenticated...
@endguest
@auth('admin')
// The user is authenticated...
@endauth
@guest('admin')
// The user is not authenticated...
@endguest
Environment Directives
You may check if the application is running in the production environment using the @production directive:
@production
// Production specific content...
@endproduction
@production
// Production specific content...
@endproduction
Or, you may determine if the application is running in a specific environment using the @env directive:
@env('staging')
// The application is running in "staging"...
@endenv
@env(['staging', 'production'])
// The application is running in "staging" or "production"...
@endenv
@env('staging')
// The application is running in "staging"...
@endenv
@env(['staging', 'production'])
// The application is running in "staging" or "production"...
@endenv
Section Directives
You may determine if a template inheritance section has content using the @hasSection directive:
@hasSection('navigation')
<div class="pull-right">
@yield('navigation')
</div>
<div class="clearfix"></div>
@endif
@hasSection('navigation')
<div class="pull-right">
@yield('navigation')
</div>
<div class="clearfix"></div>
@endif
You may use the sectionMissing directive to determine if a section does not have content:
@sectionMissing('navigation')
<div class="pull-right">
@include('default-navigation')
</div>
@endif
@sectionMissing('navigation')
<div class="pull-right">
@include('default-navigation')
</div>
@endif
Session Directives
The @session directive may be used to determine if a session value exists. If the session value exists, the template contents within the @session and @endsession directives will be evaluated. Within the @session directive’s contents, you may echo the $value variable to display the session value:
@session('status')
<div class="p-4 bg-green-100">
{{ $value }}
</div>
@endsession
@session('status')
<div class="p-4 bg-green-100">
{{ $value }}
</div>
@endsession
Switch Statements
Switch statements can be constructed using the @switch, @case, @break, @default and @endswitch directives:
@switch($i)
@case(1)
First case...
@break
@case(2)
Second case...
@break
@default
Default case...
@endswitch
@switch($i)
@case(1)
First case...
@break
@case(2)
Second case...
@break
@default
Default case...
@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:
@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
@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
While iterating through a foreach loop, 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 skip the current iteration or end the loop using the @continue and @break directives:
@foreach ($users as $user)
@if ($user->type == 1)
@continue
@endif
<li>{{ $user->name }}</li>
@if ($user->number == 5)
@break
@endif
@endforeach
@foreach ($users as $user)
@if ($user->type == 1)
@continue
@endif
<li>{{ $user->name }}</li>
@if ($user->number == 5)
@break
@endif
@endforeach
You 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)
@endforeach
@foreach ($users as $user)
@continue($user->type == 1)
<li>{{ $user->name }}</li>
@break($user->number == 5)
@endforeach
The Loop Variable
While iterating through a foreach loop, 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:
@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>
@endforeach
@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>
@endforeach
If you are in a nested loop, you may access the parent loop’s $loop variable via the parent property:
@foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is the first iteration of the parent loop.
@endif
@endforeach
@endforeach
@foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is the first iteration of the parent loop.
@endif
@endforeach
@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. |
Conditional Classes & Styles
The @class directive conditionally compiles a CSS class string. The directive accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list:
@php
$isActive = false;
$hasError = true;
@endphp
<span @class([
'p-4',
'font-bold' => $isActive,
'text-gray-500' => ! $isActive,
'bg-red' => $hasError,
])></span>
<span class="p-4 text-gray-500 bg-red"></span>
@php
$isActive = false;
$hasError = true;
@endphp
<span @class([
'p-4',
'font-bold' => $isActive,
'text-gray-500' => ! $isActive,
'bg-red' => $hasError,
])></span>
<span class="p-4 text-gray-500 bg-red"></span>
Likewise, the @style directive may be used to conditionally add inline CSS styles to an HTML element:
@php
$isActive = true;
@endphp
<span @style([
'background-color: red',
'font-weight: bold' => $isActive,
])></span>
<span style="background-color: red; font-weight: bold;"></span>
@php
$isActive = true;
@endphp
<span @style([
'background-color: red',
'font-weight: bold' => $isActive,
])></span>
<span style="background-color: red; font-weight: bold;"></span>
Additional Attributes
For convenience, you may use the @checked directive to easily indicate if a given HTML checkbox input is “checked”. This directive will echo checked if the provided condition evaluates to true:
<input
type="checkbox"
name="active"
value="active"
@checked(old('active', $user->active))
/>
<input
type="checkbox"
name="active"
value="active"
@checked(old('active', $user->active))
/>
Likewise, the @selected directive may be used to indicate if a given select option should be “selected”:
<select name="version">
@foreach ($product->versions as $version)
<option value="{{ $version }}" @selected(old('version') == $version)>
{{ $version }}
</option>
@endforeach
</select>
<select name="version">
@foreach ($product->versions as $version)
<option value="{{ $version }}" @selected(old('version') == $version)>
{{ $version }}
</option>
@endforeach
</select>
Additionally, the @disabled directive may be used to indicate if a given element should be “disabled”:
<button type="submit" @disabled($errors->isNotEmpty())>Submit</button>
<button type="submit" @disabled($errors->isNotEmpty())>Submit</button>
Moreover, the @readonly directive may be used to indicate if a given element should be “readonly”:
<input
type="email"
name="email"
value="[email protected]"
@readonly($user->isNotAdmin())
/>
<input
type="email"
name="email"
value="[email protected]"
@readonly($user->isNotAdmin())
/>
In addition, the @required directive may be used to indicate if a given element should be “required”:
<input
type="text"
name="title"
value="title"
@required($user->isAdmin())
/>
<input
type="text"
name="title"
value="title"
@required($user->isAdmin())
/>
Including Subviews
While you’re free to use the @include directive, Blade components provide similar functionality and offer several benefits over the @include directive such as data and attribute binding.
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:
<div>
@include('shared.errors')
<form>
<!-- Form Contents -->
</form>
</div>
<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'])
@include('view.name', ['status' => 'complete'])
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:
@includeIf('view.name', ['status' => 'complete'])
@includeIf('view.name', ['status' => 'complete'])
If you would like to @include a view if a given boolean expression evaluates to true or false, you may use the @includeWhen and @includeUnless directives:
@includeWhen($boolean, 'view.name', ['status' => 'complete'])
@includeUnless($boolean, 'view.name', ['status' => 'complete'])
@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 includeFirst directive:
@includeFirst(['custom.admin', 'admin'], ['status' => 'complete'])
@includeFirst(['custom.admin', 'admin'], ['status' => 'complete'])
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 @each directive:
@each('view.name', $jobs, 'job')
@each('view.name', $jobs, 'job')
The @each directive’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 of jobs, typically you will want to access each job as a job variable within the view. The array key for the current iteration will be available as the key variable within the view.
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.
@each('view.name', $jobs, 'job', 'view.empty')
@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 the @foreach and @include directives instead.
The @once Directive
The @once directive 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
@endonce
@once
@push('scripts')
<script>
// Your custom JavaScript...
</script>
@endpush
@endonce
Since the @once directive is often used in conjunction with the @push or @prepend directives, the @pushOnce and @prependOnce directives are available for your convenience:
@pushOnce('scripts')
<script>
// Your custom JavaScript...
</script>
@endPushOnce
@pushOnce('scripts')
<script>
// Your custom JavaScript...
</script>
@endPushOnce
Raw 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:
@php
$counter = 1;
@endphp
@php
$counter = 1;
@endphp
Or, if you only need to use PHP to import a class, you may use the @use directive:
@use('App\Models\Flight')
@use('App\Models\Flight')
A second argument may be provided to the @use directive to alias the imported class:
@use('App\Models\Flight', 'FlightModel')
@use('App\Models\Flight', 'FlightModel')
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 --}}
{{-- This comment will not be present in the rendered HTML --}}
Components
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: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:
php artisan make:component Alert
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. When writing components for your own application, components are automatically discovered within the app/View/Components directory and resources/views/components directory, so no further component registration is typically required.
You may also create components within subdirectories:
php artisan make:component Forms/Input
php artisan make:component Forms/Input
The command above will create an Input component in the app/View/Components/Forms directory and the view will be placed in the resources/views/components/forms directory.
If you would like to create an anonymous component (a component with only a Blade template and no class), you may use the --view flag when invoking the make:component command:
php artisan make:component forms.input --view
php artisan make:component forms.input --view
The command above will create a Blade file at resources/views/components/forms/input.blade.php which can be rendered as a component via <x-forms.input />.
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:
use Illuminate\Support\Facades\Blade;
/**
* Bootstrap your package's services.
*/
public function boot(): void
{
Blade::component('package-alert', Alert::class);
}
use Illuminate\Support\Facades\Blade;
/**
* Bootstrap your package's services.
*/
public function boot(): void
{
Blade::component('package-alert', Alert::class);
}
Once your component has been registered, it may be rendered using its tag alias:
<x-package-alert/>
<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:
use Illuminate\Support\Facades\Blade;
/**
* Bootstrap your package's services.
*/
public function boot(): void
{
Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade');
}
use Illuminate\Support\Facades\Blade;
/**
* Bootstrap your package's services.
*/
public function boot(): void
{
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 />
<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/>
<x-alert/>
<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:
<x-inputs.button/>
<x-inputs.button/>
If you would like to conditionally render your component, you may define a shouldRender method on your component class. If the shouldRender method returns false the component will not be rendered:
use Illuminate\Support\Str;
/**
* Whether the component should be rendered
*/
public function shouldRender(): bool
{
return Str::length($this->message) > 0;
}
use Illuminate\Support\Str;
/**
* Whether the component should be rendered
*/
public function shouldRender(): bool
{
return Str::length($this->message) > 0;
}
Index Components
Sometimes components are part of a component group and you may wish to group the related components within a single directory. For example, imagine a “card” component with the following class structure:
App\Views\Components\Card\Card
App\Views\Components\Card\Header
App\Views\Components\Card\Body
App\Views\Components\Card\Card
App\Views\Components\Card\Header
App\Views\Components\Card\Body
Since the root Card component is nested within a Card directory, you might expect that you would need to render the component via <x-card.card>. However, when a component’s file name matches the name of the component’s directory, Laravel automatically assumes that component is the “root” component and allows you to render the component without repeating the directory name:
<x-card>
<x-card.header>...</x-card.header>
<x-card.body>...</x-card.body>
</x-card>
<x-card>
<x-card.header>...</x-card.header>
<x-card.body>...</x-card.body>
</x-card>
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"/>
<x-alert type="error" :message="$message"/>
You should define all of the component’s data attributes 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:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class Alert extends Component
{
/**
* Create the component instance.
*/
public function __construct(
public string $type,
public string $message,
) {}
/**
* Get the view / contents that represent the component.
*/
public function render(): View
{
return view('components.alert');
}
}
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class Alert extends Component
{
/**
* Create the component instance.
*/
public function __construct(
public string $type,
public string $message,
) {}
/**
* Get the view / contents that represent the component.
*/
public function render(): View
{
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>
<div class="alert alert-{{ $type }}">
{{ $message }}
</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:
/**
* Create the component instance.
*/
public function __construct(
public string $alertType,
) {}
/**
* Create the component instance.
*/
public function __construct(
public string $alertType,
) {}
The $alertType argument may be provided to the component like so:
<x-alert alert-type="danger" />
<x-alert alert-type="danger" />
Short Attribute Syntax
When passing attributes to components, you may also use a “short attribute” syntax. This is often convenient since attribute names frequently match the variable names they correspond to:
{{-- Short attribute syntax... --}}
<x-profile :$userId :$name />
{{-- Is equivalent to... --}}
<x-profile :user-id="$userId" :name="$name" />
{{-- Short attribute syntax... --}}
<x-profile :$userId :$name />
{{-- Is equivalent to... --}}
<x-profile :user-id="$userId" :name="$name" />
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>
<x-button ::class="{ danger: isDeleting }">
Submit
</x-button>
The following HTML will be rendered by Blade:
<button :class="{ danger: isDeleting }">
Submit
</button>
<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 isSelected method:
/**
* Determine if the given option is the currently selected option.
*/
public function isSelected(string $option): bool
{
return $option === $this->selected;
}
/**
* Determine if the given option is the currently selected option.
*/
public function isSelected(string $option): bool
{
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' : '' }} value="{{ $value }}">
{{ $label }}
</option>
<option {{ $isSelected($value) ? 'selected' : '' }} value="{{ $value }}">
{{ $label }}
</option>
Accessing Attributes and 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 render method:
use Closure;
/**
* Get the view / contents that represent the component.
*/
public function render(): Closure
{
return function () {
return '<div {{ $attributes }}>Components content</div>';
};
}
use Closure;
/**
* Get the view / contents that represent the component.
*/
public function render(): Closure
{
return function () {
return '<div {{ $attributes }}>Components content</div>';
};
}
The closure returned by your component’s render method may also receive a $data array as its only argument. This array will contain several elements that provide information about the component:
return function (array $data) {
// $data['componentName'];
// $data['attributes'];
// $data['slot'];
return '<div {{ $attributes }}>Components content</div>';
}
return function (array $data) {
// $data['componentName'];
// $data['attributes'];
// $data['slot'];
return '<div {{ $attributes }}>Components content</div>';
}
The elements in the $data array should never be directly embedded into the Blade string returned by your render method, as doing so could allow remote code execution via malicious attribute content.
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 an Illuminate\Support\HtmlString instance 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.
*/
public function __construct(
public AlertCreator $creator,
public string $type,
public string $message,
) {}
use App\Services\AlertCreator;
/**
* Create the component instance.
*/
public function __construct(
public AlertCreator $creator,
public string $type,
public string $message,
) {}
Hiding Attributes / Methods
If you would like to prevent some public methods or properties from being exposed as variables to your component template, you may add them to an $except array property on your component:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
/**
* The properties / methods that should not be exposed to the component template.
*
* @var array
*/
protected $except = ['type'];
/**
* Create the component instance.
*/
public function __construct(
public string $type,
) {}
}
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
/**
* The properties / methods that should not be exposed to the component template.
*
* @var array
*/
protected $except = ['type'];
/**
* Create the component instance.
*/
public function __construct(
public string $type,
) {}
}
(本文超出站点单文档体积上限,已按小节截断)
