Laravel Blade is a powerful and easy-to-use templating engine that comes with Laravel, a popular PHP web application framework. Here is a cheat sheet of some common Blade directives and their usage:
Echoing Data:
{{ $variable }} - Outputs the value of a variable {!! $variable !!} - Outputs the value of a variable, but with HTML encoding disabled |
Control Structures:
@if ($condition) // code to execute if condition is true @endif
@unless ($condition) // code to execute if condition is false @endunless
@if ($condition) // code to execute if condition is true @elseif ($otherCondition) // code to execute if otherCondition is true @else // code to execute if both conditions are false @endif
@switch($variable) @case(value) // code to execute if $variable == value @break @case(anotherValue) // code to execute if $variable == anotherValue @break @default // code to execute if none of the above cases are true @endswitch |
Loops:
@foreach ($items as $item) // code to execute for each item in the array @endforeach
@for ($i = 0; $i < 10; $i++) // code to execute for each iteration of the loop @endfor
@while ($condition) // code to execute as long as the condition is true @endwhile |
Including Subviews:
@include('subview') @include('subview', ['key' => 'value']) |
Extending Layouts
@extends('layout') @section('content') // content to be included in the 'content' section of the layout @endsection |
Displaying Blade Syntax Errors:
@error('field_name') <div class="alert alert-danger">{{ $message }}</div> @enderror |
Commenting:
{{-- This is a Blade comment and will not be rendered in the HTML output --}} |
Displaying Partials:
@each('partials.item', $items, 'item') |
Displaying Components:
@component('components.alert') @slot('title') Alert Title @endslot
Alert body text goes here. @endcomponent |
Displaying a View Based on a Condition:
@isset($variable) @include('view') @endisset |