0
0
Laravelframework~5 mins

Blade directives in Laravel

Choose your learning style9 modes available
Introduction

Blade directives help you write clean and simple templates in Laravel. They make your HTML and PHP code easier to read and manage.

When you want to show content only if a condition is true.
When you need to loop over a list of items to display them.
When you want to include another template inside your current one.
When you want to write PHP code inside your HTML easily.
When you want to display data safely to avoid security issues.
Syntax
Laravel
@directiveName(parameters)
    <!-- content -->
@enddirectiveName
Blade directives start with an @ symbol followed by the directive name.
Some directives like @if, @foreach have matching @endif, @endforeach to close them.
Examples
Shows a message only if the user is an admin.
Laravel
@if($user->isAdmin)
    <p>Welcome, admin!</p>
@endif
Loops through each item in the list and displays it in a list item.
Laravel
@foreach($items as $item)
    <li>{{ $item }}</li>
@endforeach
Includes the content of the 'header' template here.
Laravel
@include('header')
Adds a hidden security token field to forms to protect against attacks.
Laravel
@csrf
Sample Program

This example shows how to use Blade directives to display user info, conditionally show admin message, loop through tasks, and add a CSRF token in a form.

Laravel
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blade Directives Example</title>
</head>
<body>
    @php
        $user = (object) ['name' => 'Alice', 'isAdmin' => true];
        $tasks = ['Write report', 'Attend meeting', 'Review code'];
    @endphp

    <h1>Hello, {{ $user->name }}!</h1>

    @if($user->isAdmin)
        <p>You have admin access.</p>
    @else
        <p>You are a regular user.</p>
    @endif

    <h2>Your Tasks:</h2>
    <ul>
        @foreach($tasks as $task)
            <li>{{ $task }}</li>
        @endforeach
    </ul>

    <form method="POST" action="/submit">
        @csrf
        <button type="submit">Submit</button>
    </form>
</body>
</html>
OutputSuccess
Important Notes

Always close directives like @if with @endif to avoid errors.

Use {{ }} to safely display variables and avoid security risks.

Blade compiles templates into plain PHP, so it runs fast.

Summary

Blade directives make templates easy to write and read.

Use directives for conditions, loops, includes, and security tokens.

Remember to close your directives properly.