Introduction
Blade directives help you write clean and simple templates in Laravel. They make your HTML and PHP code easier to read and manage.
Blade directives help you write clean and simple templates in Laravel. They make your HTML and PHP code easier to read and manage.
@directiveName(parameters)
<!-- content -->
@enddirectiveName@if($user->isAdmin)
<p>Welcome, admin!</p>
@endif@foreach($items as $item)
<li>{{ $item }}</li>
@endforeach@include('header')@csrf
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.
<!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>
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.
Blade directives make templates easy to write and read.
Use directives for conditions, loops, includes, and security tokens.
Remember to close your directives properly.
{{ }} to safely display variables with HTML escaping.{{ $variable }} syntax outputs the variable safely, preventing XSS attacks.$items?@foreach to loop over arrays or collections.@foreach($items as $item), which loops through each item.$count = 3?
@if($count > 5) Large @elseif($count > 1) Medium @else Small @endif
$count > 5$count = 3, 3 > 5 is false, so skip the first block.@elseif($count > 1) condition3 > 1 is true, so Blade outputs "Medium" and skips the @else.@foreach($users as $user){{ $user->name }}
@endforeach @endfor
@foreach but incorrectly ends with @endfor.@endforeach to close a @foreach loop, so @endfor is invalid here.header.blade.php inside your main view. Which directive correctly includes it and passes a variable $title with value 'Welcome'?@include accepts the view name and an associative array of data.@include('header', ['title' => 'Welcome']) with quotes around string values.Pass the test and this pattern moves unknown