Laravel Blade Syntax: A Comprehensive Guide
15 May 2025 | Category: Laravel
Blade is Laravel’s powerful templating engine, designed to create dynamic, reusable, and maintainable views with clean, expressive syntax. It allows developers to write PHP logic within HTML templates using directives, making it easy to display data, handle loops, conditionals, and layouts. This SEO-friendly, plagiarism-free guide explains Blade syntax, its key features, and how to use it effectively. Based on Laravel 11 (as of May 2025), this tutorial is tailored for beginners and intermediate developers.
What is Blade?
Blade is Laravel’s default templating engine, used to create views stored in the resources/views/
directory with a .blade.php
extension. Unlike plain PHP, Blade offers concise directives (e.g., @if
, @foreach
) that simplify logic while keeping templates readable. Blade templates are compiled into plain PHP for performance and cached until modified.
Key Benefits
- Readable Syntax: Intuitive directives reduce boilerplate code.
- Reusability: Supports layouts, partials, and components for modular views.
- Security: Automatically escapes output to prevent XSS attacks.
- Extensibility: Allows custom directives and components.
- Integration: Works seamlessly with Laravel’s MVC architecture.
Blade File Basics
Blade files are stored in resources/views/
(e.g., welcome.blade.php
). A basic Blade template combines HTML with Blade directives:
<!DOCTYPE html>
<html>
<head>
<title>My Laravel App</title>
</head>
<body>
<h1>Welcome, {{ $name }}!</h1>
</body>
</html>
{{ $name }}
: Outputs the$name
variable, automatically escaped for security.
To render a Blade view from a controller:
public function index()
{
return view('welcome', ['name' => 'John']);
}
view('welcome')
: Loadsresources/views/welcome.blade.php
.
Core Blade Syntax
Below are the most commonly used Blade directives and features, organized for clarity.
1. Displaying Data
- Output Escaped Data:
{{ $variable }}
Escapes HTML to prevent XSS (e.g., <script>
becomes <script>
).
- Output Unescaped Data (use cautiously):
{!! $variable !!}
Renders raw HTML (e.g., for trusted content like formatted text).
- Default Values:
{{ $variable ?? 'Default' }}
Displays 'Default'
if $variable
is null or undefined.
- Ternary Operator:
{{ $user ? $user->name : 'Guest' }}
2. Conditionals
Blade provides @if
, @else
, @elseif
, and @unless
for conditional logic.
Example:
@if($user)
<p>Welcome, {{ $user->name }}!</p>
@elseif($guest)
<p>Hello, Guest!</p>
@else
<p>Please log in.</p>
@endif
@unless (opposite of @if
):
@unless($user)
<p>Please log in.</p>
@endunless
Shorthand (single-line):
{{ $user ? 'Logged in' : 'Logged out' }}
3. Loops
Blade supports @for
, @foreach
, @while
, and @forelse
for iterating over data.
@foreach:
<ul>
@foreach($posts as $post)
<li>{{ $post->title }}</li>
@endforeach
</ul>
@forelse (handles empty collections):
@forelse($posts as $post)
<li>{{ $post->title }}</li>
@empty
<p>No posts found.</p>
@endforelse
Loop Variables:
The $loop
object provides metadata within loops:
@foreach($posts as $post)
<li>
{{ $post->title }}
(Index: {{ $loop->index }},
Remaining: {{ $loop->remaining }},
First: {{ $loop->first ? 'Yes' : 'No' }})
</li>
@endforeach
$loop->index
: Zero-based index.$loop->iteration
: One-based iteration.$loop->remaining
: Items left.$loop->first
/last
: Boolean for first/last item.
4. Including Sub-Views
Include partial views for reusable components:
@include('partials.header')
Pass data to included views:
@include('partials.header', ['title' => 'My Page'])
Conditional Include:
@includeIf('partials.header', ['title' => 'My Page'])
Only includes if the view exists.
5. Layouts and Inheritance
Blade supports layouts for consistent page structure using @extends
, @section
, and @yield
.
Layout File (resources/views/layouts/app.blade.php
):
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
Child View:
@extends('layouts.app')
@section('title', 'Home Page')
@section('content')
<h1>Welcome to my app!</h1>
@endsection
@extends
: Inherits the layout.@section
: Defines content for a@yield
placeholder.@yield('title', 'Default')
: Provides a default value if the section is undefined.
Appending to Sections:
@section('scripts')
@parent
<script src="/extra.js"></script>
@endsection
@parent
: Includes the parent section’s content.
6. Components
Blade components encapsulate reusable UI elements (e.g., buttons, modals).
Create Component:
php artisan make:component Alert
This generates:
app/View/Components/Alert.php
: Component logic.resources/views/components/alert.blade.php
: Component template.
Component Template (alert.blade.php
):
<div class="alert alert-{{ $type }}">
{{ $slot }}
</div>
Component Class (Alert.php
):
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
public $type;
public function __construct($type = 'info')
{
$this->type = $type;
}
public function render()
{
return view('components.alert');
}
}
Usage:
<x-alert type="success">
Operation successful!
</x-alert>
x-
: Prefix for components.$slot
: Content passed between opening/closing tags.
7. Forms and CSRF Protection
Blade simplifies form creation with CSRF protection (required for web
routes).
Example Form:
<form method="POST" action="{{ route('posts.store') }}">
@csrf
<input type="text" name="title" value="{{ old('title') }}">
<textarea name="content">{{ old('content') }}</textarea>
<button type="submit">Save</button>
</form>
@csrf
: Adds a hidden CSRF token.old('title')
: Repopulates form input after validation failure.
Method Spoofing (for PUT/DELETE):
<form method="POST" action="{{ route('posts.update', $post) }}">
@csrf
@method('PUT')
<input type="text" name="title" value="{{ $post->title }}">
<button type="submit">Update</button>
</form>
@method('PUT')
: Spoofs the HTTP method.
8. Error Handling
Display validation errors:
@if($errors->any())
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
Field-specific errors:
<input type="text" name="title">
@error('title')
<span class="error">{{ $message }}</span>
@enderror
9. Comments
Blade comments are not included in the compiled output:
{{-- This is a Blade comment --}}
10. Raw PHP
Use raw PHP sparingly:
@php
$counter = 0;
@endphp
Advanced Blade Features
Custom Directives
Create custom directives for reusable logic.
Define in app/Providers/AppServiceProvider.php
:
public function boot()
{
Blade::directive('uppercase', function ($expression) {
return "<?php echo strtoupper($expression); ?>";
});
}
Use:
@uppercase('hello')
Output: HELLO
.
Stacks
Manage scripts or styles in layouts:
<!-- Layout -->
@stack('scripts')
<!-- Child View -->
@push('scripts')
<script src="/app.js"></script>
@endpush
Service Injection
Inject dependencies directly:
@inject('cache', 'Illuminate\Contracts\Cache\Repository')
{{ $cache->get('key') }}
Best Practices for Blade Syntax
- Keep Logic Minimal: Move complex logic to controllers or helpers.
- Use Components: Encapsulate reusable UI with components.
- Escape Output: Prefer
{{ }}
over{!! !!}
for security. - Leverage Layouts: Use
@extends
for consistent page structure. - Handle Errors Gracefully: Always display validation errors.
- Organize Views: Group related views in subdirectories (e.g.,
resources/views/posts/
). - Cache Templates: Ensure views are cached in production (
php artisan view:cache
).
Conclusion
Blade’s expressive syntax makes it easy to build dynamic, reusable, and secure views in Laravel. From displaying data and handling conditionals to creating layouts and components, Blade simplifies front-end development while integrating seamlessly with Laravel’s MVC architecture. By mastering Blade directives, you can create clean, maintainable templates for web applications.
Next Steps:
- Create a Blade template in
resources/views/
. - Experiment with layouts and components.
- Explore Laravel’s official documentation for advanced Blade features.
For further learning, join the Laravel community on platforms like X or dive into the official Laravel documentation. Start crafting views with Blade today!