Laravel 12 Blade Directives: From Beginner to Advanced
Laravel is one of the most popular PHP frameworks, and its templating engine, Blade, is a big reason why. Blade makes it easy to create clean, readable, and dynamic templates for your web applications. One of its standout features is directives—special commands that start with the @ symbol. These directives let you handle tasks like displaying data, adding conditions, looping through arrays, and reusing parts of your design with a simple, elegant syntax.
In this blog post, we’ll explore Blade directives in Laravel 12—starting with the basics for beginners and gradually moving to more advanced topics. Whether you’re new to Laravel or looking to level up your skills, this guide will break everything down in simple terms with detailed examples. Let’s dive in!
What Are Blade Directives?
Blade directives are shortcuts that make it easier to write PHP code in your templates. They all start with the @ symbol, followed by a command like @if or @foreach. Instead of writing raw PHP with <?php ... ?> tags, Blade gives you a cleaner way to display data (e.g., {{ \$name }}), check conditions (e.g., @if), loop through arrays (e.g., @foreach), and include other files (e.g., @include).
Blade processes these directives into regular PHP code and caches them for improved performance, ensuring your application runs quickly while keeping your code readable.
Basic Directives for Beginners
Here are the essential Blade directives that every beginner should know:
Conditionals: @if, @else, @elseif, @endif
The @if directive lets you conditionally display content:
<?php
@if($user->isAdmin)
<p>Hello, Admin!</p>
@elseif($user->isEditor)
<p>Hello, Editor!</p>
@else
<p>Hello, User!</p>
@endif
Loops: @foreach, @for, @while
Blade simplifies looping through data:
<?php
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach
@for($i = 1; $i <= 5; $i++)
<p>Number {{ $i }}</p>
@endfor
@while($count < 3)
<p>Count: {{ $count }}</p>
@php $count++; @endphp
@endwhile
Reusing Views: @include
The @include directive lets you insert another Blade file into your template:
<?php
@include('partials.header')
You can also pass data:
<?php
@include('partials.header', ['title' => 'Home Page'])
Layouts: @extends, @section, @yield
Blade’s layout system allows you to create a master template and then extend it in child views.
<!-- resources/views/layouts/main.blade.php -->
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
<!-- Child view: resources/views/home.blade.php -->
@extends('layouts.main')
@section('title')
My Blog
@endsection
@section('content')
<h1>Welcome to My Blog!</h1>
@endsection
Intermediate Directives
Managing Scripts: @stack and @push
These directives allow you to insert scripts or styles in specific parts of your layout.
<!-- In your layout -->
@stack('scripts')
<!-- In a child view -->
@push('scripts')
<script src="/app.js"></script>
@endpush
User Checks: @auth and @guest
These directives display content based on user authentication:
<?php
@auth
<p>Hi, {{ auth()->user()->name }}!</p>
@endauth
@guest
<p>Please log in or sign up.</p>
@endguest
Forms: @csrf and @method
These directives simplify form security and HTTP method spoofing:
<form method="POST" action="/save">
@csrf
<input type="text" name="title">
<button>Save</button>
</form>
<form method="POST" action="/update">
@method('PUT')
@csrf
<input type="text" name="title">
<button>Update</button>
</form>
Validation: @error
The @error directive displays validation error messages:
<input type="text" name="email">
@error('email')
<p class="error">{{ $message }}</p>
@enderror
Advanced Features
Custom Directives
You can create your own Blade directives to simplify repetitive tasks. For example, add a custom date formatting directive in your AppServiceProvider:
<?php
use Illuminate\Support\Facades\Blade;
public function boot()
{
Blade::directive('datetime', function ($expression) {
return "format('F j, Y'); ?>";
});
}
Use it in your view as:
@datetime($post->created_at)
Blade Components
Components allow you to create reusable UI elements. Create a component with:
php artisan make:component Alert
Then, in resources/views/components/alert.blade.php:
<div class="alert">
{{ $message }}
</div>
Use the component in your view:
<x-alert message="Success!" />
Special Tools: @json and @verbatim
The @json directive converts PHP data to JSON:
<script>
let users = @json($users);
</script>
The @verbatim directive lets you display Blade code without processing it:
@verbatim
@if($user)
Hello, {{ $user->name }}!
@endif
@endverbatim
Raw PHP: @php
Use the @php directive to write raw PHP code in your template:
@php
$total = $price * $quantity;
@endphp
<p>Total: {{ $total }}</p>
Handy Extras
Checking Variables: @isset and @empty
@isset($user)
<p>User found!</p>
@endisset
@empty($cart)
<p>Your cart is empty.</p>
@endempty
Flipping Conditions: @unless
@unless($user->isActive)
<p>Please activate your account.</p>
@endunless
One-Time Content: @once
@once
<script src="/app.js"></script>
@endonce
Tips for Using Blade Safely
- Keep It Simple: Avoid complex logic in your templates; use controllers or helpers instead.
- Stay Secure: Blade’s {{ '{{' }} }} automatically escapes output to prevent XSS attacks. Use {!! !!} only when you trust the content.
- Clear Cache: If changes don’t appear, run
php artisan view:clearto clear cached views.
Wrapping Up
Laravel 12’s Blade directives make templating a breeze—from simple @if statements to custom directives and components. They help you write clean, reusable, and efficient views without getting bogged down in raw PHP.
Start with the basics, experiment with intermediate tools, and explore advanced features to see what works best for your projects. Blade is all about making your life easier as a developer—so dive in, try these examples, and build something awesome with Laravel!
Happy coding!
Projects related to this guide
Use the concepts from this article in practical source-code projects.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure...
Python Flask Blog Project with Admin Panel
Are you ready to launch a powerful, modern, and fully customizable blog? Look no further! Introducing the Flask-...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes pr...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.