Laravel Blade is a powerful templating engine that comes with the Laravel framework. It simplifies the process of creating dynamic and reusable views in your web applications. Blade is intuitive and integrates seamlessly with Laravel’s MVC architecture, making it easier to develop clean and maintainable code.
In this blog, we’ll explore the fundamentals of Blade templates, including syntax, control structures, and some advanced features. We’ll walk through practical examples to help you get the most out of Blade.
What is Blade?
Blade is Laravel’s templating engine that allows you to write PHP code in your views in a clean and expressive manner. Blade templates are compiled into plain PHP code and cached for performance. It is very useful and easy to feature in Laravel Framework.
Basic Syntax:
Blade templates use the .blade.php
file extension and offer a concise syntax that makes it easy to work with HTML and PHP. Blade templates are typically stored in the resources/views
directory of a Laravel project.
Example:
<!-- resources/views/welcome.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Hello, {{ $name }}!</h1>
<p>Welcome to Blade Template.</p>
</body>
</html>
In the example above, {{ $name }}
is a Blade directive that outputs the value of the $name
variable.
Blade Syntax and Directives
1. Displaying Data
Blade’s double curly braces {{ }}
are used to escape and display data. If you want to display raw, unescaped data, you can use {!! !!}
.
Example:
<p>{{ $user->name }}</p> <!-- Escaped output -->
<p>{!! $user->description !!}</p> <!-- Unescaped output -->
2. Control Structures
Blade provides control structures similar to PHP’s, but with a more readable syntax.
- If Statements:
@if ($user->isAdmin())
<p>Welcome, Admin!</p>
@elseif ($user->isEditor())
<p>Welcome, Editor!</p>
@else
<p>Welcome, User!</p>
@endif
- Loops:
@foreach ($users as $user)
<p>{{ $user->name }}</p>
@endforeach
- Forelse:
@forelse ($users as $user)
<p>{{ $user->name }}</p>
@empty
<p>No users found.</p>
@endforelse
3. Including Subviews
Blade Template allows you to include other Blade views within a view.
Example:
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
<!-- resources/views/home.blade.php -->
@extends('layouts.app')
@section('title', 'Home Page')
@section('content')
<h1>Welcome to the Home Page</h1>
<p>This is the home page content.</p>
@endsection
In this example, @extends
indicates that home.blade.php
extends the layouts.app
view, and @section
defines sections of the content to be injected into the layout.
4. Components and Slots
Blade Template components help you create reusable pieces of UI.
Example:
- Creating a Component:
// artisan command
php artisan make:component Alert
- Component View:
<!-- resources/views/components/alert.blade.php -->
<div class="alert {{ $type }}">
{{ $slot }}
</div>
- Using the Component:
<x-alert type="warning">
This is a warning message!
</x-alert>
5. Blade Directives
Blade comes with several built-in directives:
- @csrf: Adds a CSRF token to your form.
<form method="POST" action="/submit">
@csrf
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
- @auth and @guest: Display content based on authentication status.
@auth
<p>Welcome, {{ auth()->user()->name }}!</p>
@else
<p>Please <a href="/login">login</a>.</p>
@endauth
Advanced Blade Features

1. Blade Extensions: You can extend Blade’s functionality by creating your own custom directives. This is done by adding directives in a service provider.
Example:
// App\Providers\AppServiceProvider.php
use Illuminate\Support\Facades\Blade;
public function boot()
{
Blade::directive('uppercase', function ($expression) {
return "<?php echo strtoupper($expression); ?>";
});
}
Usage:
@uppercase('hello world')
2. View Composers: Use view composers to bind data to views automatically.
Example:
// App\Providers\AppServiceProvider.php
use Illuminate\Support\Facades\View;
public function boot()
{
View::composer('partials.sidebar', function ($view) {
$view->with('categories', \App\Models\Category::all());
});
}
Handling Form Errors and Validation
<!-- resources/views/forms/contact.blade.php -->
<form method="POST" action="{{ route('contact.submit') }}">
@csrf
<div class="mb-4">
<label for="name" class="block text-gray-700">Name</label>
<input type="text" id="name" name="name" class="form-input" value="{{ old('name') }}">
@error('name')
<p class="text-red-500 text-sm">{{ $message }}</p>
@enderror
</div>
<div class="mb-4">
<label for="email" class="block text-gray-700">Email</label>
<input type="email" id="email" name="email" class="form-input" value="{{ old('email') }}">
@error('email')
<p class="text-red-500 text-sm">{{ $message }}</p>
@enderror
</div>
<button type="submit" class="btn-primary">Submit</button>
</form>
Implementing Custom Blade Directives for Reusable Logic
Guide on how to define and use custom Blade Template directives for tasks like formatting dates or generating custom HTML snippets. Create custom Blade directives to simplify repetitive tasks or add new functionality to your templates.
Content: Guide on how to define and use custom Blade directives for tasks like formatting dates or generating custom HTML snippets.
// App\Providers\AppServiceProvider.php
use Illuminate\Support\Facades\Blade;
public function boot()
{
Blade::directive('formatDate', function ($expression) {
return "<?php echo ($expression)->format('d/m/Y'); ?>";
});
}
<!-- Using the custom directive -->
<p>Published on: @formatDate($post->published_at)</p>
Testing Blade Views with PHPUnit
- Example: Write PHPUnit tests to ensure that Blade views render correctly and include expected data.
- Content: Provide examples of how to test Blade views for content, layout, and dynamic data using testing features.
// tests/Feature/ViewTest.php
namespace Tests\Feature;
use Tests\TestCase;
class ViewTest extends TestCase
{
/** @test */
public function it_displays_the_home_page()
{
$response = $this->get('/');
$response->assertStatus(200)
->assertSee('Welcome to Laravel');
}
}
Building an Admin Dashboard with Blade and Chart.js
- Example: Integrate Chart.js with Blade templates to build a data visualization dashboard.
- Content: Show how to set up and use Chart.js within Blade views to display charts and graphs.
<!-- resources/views/admin/dashboard.blade.php -->
@extends('layouts.admin')
@section('title', 'Dashboard')
@section('content')
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
@endsection
Integrating Laravel Blade with a CMS-like System
- Example: Build a simple CMS with Blade templates for managing content, such as pages and blog posts. In CMS like system, the data are displaying dynamically mostly the Laravel is using Eloquent ORM library to play with dynamic data.
- Content: Illustrate how to use Blade to create an admin interface for managing content and displaying it dynamically on the site.
<!-- resources/views/admin/pages.blade.php -->
@extends('layouts.admin')
@section('title', 'Manage Pages')
@section('content')
<h2>Pages</h2>
<table>
<thead>
<tr>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($pages as $page)
<tr>
<td>{{ $page->title }}</td>
<td>
<a href="{{ route('admin.pages.edit', $page->id) }}">Edit</a>
<form action="{{ route('admin.pages.destroy', $page->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@endsection
Building a Notification System with Blade and Laravel Events
- Example: Create a notification system that displays user notifications using Laravel events and Blade templates.
- Content: Demonstrate how to use Blade templates to display notifications, and set up events to trigger notifications.
<!-- resources/views/notifications.blade.php -->
@extends('layouts.app')
@section('content')
<h1>Notifications</h1>
@foreach ($notifications as $notification)
<div class="notification">
<p>{{ $notification->message }}</p>
<span>{{ $notification->created_at->diffForHumans() }}</span>
</div>
@endforeach
@endsection
These topics offer a broad range of practical examples and use cases for Blade templates. Each example is designed to illustrate a specific feature or capability of Blade, helping you build more dynamic, efficient, and maintainable views in your applications.
// App\Providers\AppServiceProvider.php
use Illuminate\Support\Facades\Blade;
public function boot()
{
Blade::directive('formatDate', function ($expression) {
return "<?php echo ($expression)->format('d/m/Y'); ?>";
});
}
<!-- Using the custom directive -->
<p>Published on: @formatDate($post->published_at)</p>
Integrating Blade with a CMS-like System
Build a simple CMS with Blade templates for managing content, such as pages and blog posts.
<!-- resources/views/admin/pages.blade.php -->
@extends('layouts.admin')
@section('title', 'Manage Pages')
@section('content')
<h2>Pages</h2>
<table>
<thead>
<tr>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($pages as $page)
<tr>
<td>{{ $page->title }}</td>
<td>
<a href="{{ route('admin.pages.edit', $page->id) }}">Edit</a>
<form action="{{ route('admin.pages.destroy', $page->id) }}" method="POST" style="display:inline;">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@endsection
Building a Notification System with Blade and Events
Create a notification system that displays user notifications using events and Blade templates.
<!-- resources/views/notifications.blade.php -->
@extends('layouts.app')
@section('content')
<h1>Notifications</h1>
@foreach ($notifications as $notification)
<div class="notification">
<p>{{ $notification->message }}</p>
<span>{{ $notification->created_at->diffForHumans() }}</span>
</div>
@endforeach
@endsection
Creating a Layout System with Multiple Blade Layouts
Build a complex layout system using multiple Blade layout files for different sections of an application, such as admin panels and user dashboards.
<!-- resources/views/layouts/admin.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>@yield('title') | Admin Panel</title>
</head>
<body>
<header>
<h1>Admin Panel</h1>
<!-- Admin-specific navigation -->
</header>
<main>
@yield('content')
</main>
<footer>
© {{ date('Y') }} Admin
</footer>
</body>
</html>
<!-- resources/views/admin/dashboard.blade.php -->
@extends('layouts.admin')
@section('title', 'Dashboard')
@section('content')
<h2>Dashboard</h2>
<p>Welcome to the admin dashboard.</p>
@endsection
Using Blade Components for UI Elements like Modals and Alerts
Create reusable Blade components for common UI elements such as modals and alerts.
// Artisan command
php artisan make:component Modal
<!-- resources/views/components/modal.blade.php -->
<div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" x-data="{ open: @entangle('open') }">
<div class="bg-white p-4 rounded shadow-md">
<div class="flex justify-between items-center">
<h2 class="text-lg font-semibold">{{ $title }}</h2>
<button @click="open = false" class="text-gray-600">×</button>
</div>
<div class="mt-4">
{{ $slot }}
</div>
</div>
</div>
Conclusion
Laravel Blade is a robust templating engine that enhances the development experience with it. By using Blade, you can create clean, dynamic views while keeping your codebase organized and maintainable. Whether you’re displaying data, handling conditional logic, or creating reusable components, Blade provides a powerful yet straightforward approach to view management.