Kritim Yantra
Mar 11, 2025
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!
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.
Here are the essential Blade directives that every beginner should know:
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
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
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'])
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
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
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
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>
The @error directive displays validation error messages:
<input type="text" name="email">
@error('email')
<p class="error">{{ $message }}</p>
@enderror
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)
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!" />
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
Use the @php directive to write raw PHP code in your template:
@php
$total = $price * $quantity;
@endphp
<p>Total: {{ $total }}</p>
@isset($user)
<p>User found!</p>
@endisset
@empty($cart)
<p>Your cart is empty.</p>
@endempty
@unless($user->isActive)
<p>Please activate your account.</p>
@endunless
@once
<script src="/app.js"></script>
@endonce
php artisan view:clear
to clear cached views.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!
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google