Laravel Blade Syntax & Directives | Laravel Layouts

Laravel balde directives

📑 Table of Contents

  1. Introduction
  2. Blade Directives
       2.1 Output & Comments Directives
     2.2 Conditional Directives
     2.3 Loop Directives
     2.4 Authorization Directives
     2.5 Error & Validation Directives
     2.6 Inline PHP & Verbatim Directives
     2.7 Environment & Class Directives
     2.8 CSRF and Method Directives
     2.9 Blade Custom Directives
  3. Layouts in Laravel
  4. Blade Layout Directives (@extends, @section, @yield)
  5. Including Partials with @include
  6. Laravel Blade Components & Slots
  7. Using Blade Stacks: @push, @prepend, @stack
  8. Building a Complete Master Layout in Laravel
  9. Summary & Best Practices

1. Introduction to Laravel Blade

Blade is the templating engine that comes built-in with Laravel. It helps you build clean and dynamic web pages using PHP and HTML together.

Instead of mixing messy PHP code inside your HTML, Blade gives you directives (special keywords starting with @) to write logic in a cleaner way.

If you are new to Laravel, think of Blade as a tool that makes your views easy to manage and your code easy to read.


2. What Are Blade Directives in Laravel

Blade directives are shortcuts for common PHP tasks like showing data, looping, or checking conditions.

They always start with @ and are processed by Laravel before the final HTML is sent to the browser.

Example:

@if($age > 18) <p>Adult</p> @endif 

This works like an if statement in PHP, but looks cleaner.

Laravel has dozens of built-in directives, and you can even create your own custom blade directives.


3. Laravel Blade Directives List with Examples

Here are the most useful Laravel blade directives divided into categories.


3.1 Output & Comments Directives 

Directive Purpose Example Output
{{ }} Echo escaped data {{ $name }} Ahmad
{!! !!} Echo unescaped data (HTML allowed) {!! $html !!} <b>Hi</b>
@{{ }} Show Blade syntax as text @{{ $name }} {{ $name }}
{{-- --}} Add a comment (not shown in HTML) {{-- This is a comment --}} (Nothing)

Use {{ }} most of the time to prevent XSS attacks.


3.2 Conditional Directives

In Laravel Blade, conditional directives are used to show or hide parts of the view based on certain conditions.

They work just like if statements in PHP but are written in Blade syntax, making your view files clean, readable, and dynamic.

Why Use Conditional Directives?

  • To display different content based on user roles (admin, guest)

  • To check if data exists before showing it

  • To handle empty arrays or collections

  • To secure sections of a page for logged-in users only

These directives allow logic inside Blade templates without writing messy PHP code.

(i) @if / @elseif / @else / @endif

Used for basic conditional checks.

Example:

@if($age > 18)
    <p>Adult</p>
@elseif($age == 18)
    <p>Just turned 18</p>
@else
    <p>Minor</p>
@endif

How it works:

  • Checks $age > 18 → if true shows "Adult"

  • Otherwise checks $age == 18 → if true shows "Just turned 18"

  • Otherwise → shows "Minor"

Use case: Display content based on user age, role, status, etc.


(ii) @unless

Reverse of if — runs only if the condition is false.

Example:

@unless($isAdmin)
    <p>You are not an admin</p>
@endunless
 

How it works:

  • If $isAdmin is false, the content inside runs.

  • If $isAdmin is true, nothing is shown.

Use case: Display warnings or restrictions for non-admin users.


(iii) @isset / @empty

Check if a variable is set or empty before using it.

Example:

@isset($name)
    <p>{{ $name }}</p>
@endisset

@empty($posts)
    <p>No posts found</p>
@endempty

How it works:

  • @isset($name) → shows content only if $name exists and is not null

  • @empty($posts) → shows content if $posts is empty (null or count 0)

✅ Use case: Avoid "undefined variable" errors and show default content.


(iv) @auth / @guest

Used to show content based on authentication status.

Example:

@auth
    <p>Welcome back!</p>
@endauth

@guest
    <p>Please log in</p>
@endguest

How it works:

  • @auth shows content if user is logged in

  • @guest shows content if user is not logged in

✅ Use case: Show different navigation menus or buttons for guests vs. users.


Summary Table of Blade Conditional Directives

Directive Purpose Example
@if Basic conditional check @if($value > 10)
@elseif Additional condition if previous is false @elseif($value == 10)
@else Default block if all conditions are false @else
@unless Reverse condition (if false) @unless($admin)
@isset Runs if variable exists and not null @isset($name)
@empty Runs if variable is empty @empty($data)
@auth Runs if user is logged in @auth
@guest Runs if user is guest (not logged in) @guest

Tips & Best Practices

  • Always check if a variable exists with @isset before using it to avoid errors.

  • Use @empty when showing default content for empty arrays or collections.

  • Combine @auth and @guest for building authentication-based layouts.

  • Keep conditions inside views simple — move complex logic to controllers.


3.3 Loop Directives

When building web applications, you’ll often need to display data repeatedly—like showing a list of blog posts, user comments, or product items. Instead of writing the same code again and again, Blade provides powerful loop directives that make this super easy.

 Why Loops in Blade?

Loops allow you to iterate over arrays, collections, or numeric ranges. In Laravel, Blade provides special directives like @for, @foreach, @forelse, and @while to handle different looping situations.

(i). The @for Loop

The @for directive works just like a normal PHP for loop. You can use it when you know exactly how many times you want to repeat something.

Example:

<ul>
    @for ($i = 1; $i <= 5; $i++)
        <li>Item {{ $i }}</li>
    @endfor
</ul>

Output:

 Item 1 Item 2 Item 3 Item 4 Item 5

(ii). The @foreach Loop

This is the most common loop in Blade. It’s used to iterate over arrays or collections.

Example:

@php
    $users = ['Ahmad', 'Ali', 'Sara'];
@endphp

<ul>
    @foreach ($users as $user)
        <li>{{ $user }}</li>
    @endforeach
</ul>

Output: 

Ahmad Ali Sara

 You can also access the key and value when looping: 

@foreach ($users as $index => $user)
    <p>User {{ $index + 1 }}: {{ $user }}</p>
@endforeach

(iii). The @forelse Loop

The @forelse loop is like @foreach, but it also handles the case when the array is empty.

Example: 

@php
    $products = [];
@endphp

<ul>
    @forelse ($products as $product)
        <li>{{ $product }}</li>
    @empty
        <p>No products available.</p>
    @endforelse
</ul>

Output:

 No products available.

(iv). The @while Loop

The @while directive works like a normal PHP while loop. You use it when you want to repeat until a condition becomes false.

Example:

@php
    $count = 1;
@endphp

<ul>
    @while ($count <= 3)
        <li>Count: {{ $count }}</li>
        @php $count++; @endphp
    @endwhile
</ul>

Output:

 Count: 1 Count: 2 Count: 3

(v). Loop Variables in Blade ($loop)

Inside a @foreach loop, Blade gives you a special $loop variable with useful properties.

Example: 

@foreach ($users as $user)
    <p>
        {{ $loop->iteration }}. {{ $user }}
        @if ($loop->first) (First User) @endif
        @if ($loop->last) (Last User) @endif
    </p>
@endforeach

Available $loop properties:

  • $loop->index → Current loop index (starts at 0)

  • $loop->iteration → Current loop count (starts at 1)

  • $loop->remaining → Items left in the loop

  • $loop->count → Total items in the loop

  • $loop->firsttrue if it’s the first item

  • $loop->lasttrue if it’s the last item


(vi). Breaking and Continuing Loops

Just like in PHP, you can use @break and @continue in Blade loops.

Example:

@foreach ($users as $user)
    @if ($user == 'Ali')
        @continue  {{-- Skip Ali --}}
    @endif

    @if ($user == 'Sara')
        @break     {{-- Stop the loop at Sara --}}
    @endif

    <p>{{ $user }}</p>
@endforeach
 

Directive Purpose Example
@for Classic for loop @for($i=0;$i<5;$i++)
@foreach Loop through arrays @foreach($users as $user)
@forelse Loop or show empty state @forelse($items as $item) @empty No items @endforelse
@while While loop @while($count<3)

$loop->iteration, $loop->count, $loop->first, $loop->last are handy properties.

Summary

  • Use @for when you need a fixed loop.

  • Use @foreach for iterating arrays/collections.

  • Use @forelse when you also want to handle empty arrays.

  • Use @while for condition-based repetition.

  • $loop provides useful details inside @foreach.

  • Use @break and @continue to control loop flow.

👉 With loops in Blade, you can efficiently display dynamic data without repeating yourself. They are essential for rendering lists, tables, menus, and more in Laravel applications


3.4 Authorization Directives 

Blade also includes security checks called authorization directives.

Directive Description Example
@can If user has permission @can('update',$post)
@cannot If user does NOT have permission @cannot('delete',$post)
@canany If user has any permission from a list @canany(['edit','create'])

 

Example:

@can('update-post', $post)
  <button>Edit</button>
@endcan

This is known as the laravel can directive. It works with Laravel policies and gates.


3.5 Error & Validation Directives (@error , @enderror)

For showing validation messages from forms:

@error('email')
  <p class="error">{{ $message }}</p>
@enderror

Show all errors:

@if($errors->any())
  <ul>
    @foreach($errors->all() as $err)
      <li>{{ $err }}</li>
    @endforeach
  </ul>
@endif

3.6 Inline PHP & Verbatim Directives (@php , @endphp)

Sometimes you need raw PHP:

@php
  $today = now();
@endphp
<p>Today: {{ $today->format('d M Y') }}</p>

Prevent Blade from parsing:

@verbatim
  <div>{{ This will not be parsed }}</div>
@endverbatim

3.7 Environment & Class Directives (@env , @production)

Laravel provides directives for environment checks and classes:

@env('local')
  <p>Local Mode</p>
@endenv

@production
  <p>Live Website</p>
@endproduction

<div @class(['active' => $isActive, 'disabled'])>Link</div>

Here @class is a laravel class directive to add CSS conditionally.


3.8 CSRF and Method Directives (@csrf, @method)

These help secure Laravel forms:

<form method="POST">
  @csrf
  @method('PUT')
</form>

@csrf generates a token to prevent CSRF attacks.
@method lets you fake PUT/DELETE from forms (HTML only supports GET/POST).


3.9 Blade Custom Directives

You can create your own laravel blade custom directive inside AppServiceProvider.

use Illuminate\Support\Facades\Blade;

public function boot()
{
    Blade::directive('uppercase', function ($expr) {
        return "<?php echo strtoupper($expr); ?>";
    });
}

Usage

 
@uppercase('hello world') 

This prints: HELLO WORLD
Creating laravel custom directives lets you reuse your own code shortcuts.


4. What Is a Layout in Laravel

Now that you know the common blade directives in Laravel, let’s see how to combine them into layouts.

A Laravel layout is a base template (HTML skeleton) that your pages extend. It avoids code repetition.
You write your site’s header, navbar, and footer in one file — called a Laravel master layout — and then all pages can use it.

Benefits of Laravel Blade layout:

  • Centralized design

  • Faster development

  • Easier maintenance

  • Consistent structure across all pages


5. Laravel Blade Layout Example (Step-by-Step)

Follow this step to create layout in Laravel:

Step 1 — Make layout file

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>@yield('title','My Laravel App')</title>
</head>
<body>
  <header>
    <h1>Laravel Blade Layout</h1>
    @include('partials.navbar')
  </header>

  <main>
    @yield('content')
  </main>

  <footer>
    <p>&copy; {{ date('Y') }}</p>
  </footer>
</body>
</html>

Step 2 — Use layout in a view

resources/views/home.blade.php

@extends('layouts.app')

@section('title','Home Page')

@section('content')
  <h2>Welcome to the Home Page</h2>
  <p>This page uses Laravel Blade layout example.</p>
@endsection

This is the simplest laravel blade template layout example.
The @extends directive connects the child view to the laravel master layout.


6. Blade Layout Directives (@extends, @section, @yield)

Directive Description Example
@extends Extends a layout file @extends('layouts.app')
@section Defines a content block @section('content') ... @endsection
@yield Shows the content in layout @yield('content')

They are the heart of laravel view layout.
Every page just fills sections like content, title, or sidebar.


7. Including Partials with @include

Instead of repeating the same HTML, break them into partials:

@include('partials.header')
@include('partials.footer')

Variants:

@includeIf('partials.ad')
@includeWhen($loggedIn,'partials.profile')
@includeUnless($isAdmin,'partials.notice')

This keeps your layout laravel files clean and modular.


8. Laravel Blade Components & Slots

Components are reusable mini-views with their own logic.

resources/views/components/alert.blade.php

<div class="alert alert-{{ $type }}">
  {{ $slot }}
</div>

Usage

<x-alert type="success">
  Profile updated successfully!
</x-alert>

You can also define props using @props.

@props(['title'])

<div class="card">
  <h3>{{ $title }}</h3>
  {{ $slot }}
</div>

These are called laravel layout components and are great for reusable UI parts like buttons, modals, cards.


9. Using Blade Stacks: @push, @prepend, @stack

Stacks are used for adding scripts or styles from child pages to your layout.

In layout

<head>
  @stack('styles')
</head>
<body>
  @stack('scripts')
</body>

In page

@push('scripts')
<script src="/page.js"></script>
@endpush

@prepend('styles')
<link rel="stylesheet" href="/page.css">
@endprepend

This helps keep your laravel app layout clean and page-specific.


10. Building a Complete Master Layout in Laravel

Here’s how a full laravel default layout project structure looks:

resources/views/
  layouts/
    app.blade.php
  partials/
    navbar.blade.php
  components/
    alert.blade.php
  pages/
    home.blade.php
    about.blade.php

Your layout (app.blade.php) contains @include('partials.navbar'),
Pages extend the layout with @extends('layouts.app'),
Components are used as <x-alert> anywhere.

This is the standard approach in most Laravel view layout systems.


11. Summary & Best Practices

  • Learn directives first, then use them to build layouts.

  • Use @extends, @section, @yield to structure pages.

  • Use @include for repeated HTML parts like navbar, footer.

  • Use Blade components for reusable UI widgets.

  • Always use {{ }} for safe output and {!! !!} only when needed.

  • Group your views in folders like layouts, partials, pages for clean project structure.

  • Use @can, @csrf, @error, @class etc. when building forms or secure views.

With this knowledge, you now understand both Blade directives Laravel offers and how to build a complete Laravel blade layout system from scratch.