Unpopular Laravel Blade Directives

Blade is the template engine that comes with any Laravel installs. Using Blade will make displaying data to HTML a breeze.

Following are some Blade directives that aren’t commonly used despite their advantages:

@each

The @each directive iterates through a collection and assigns a given view to a single item.

It can even send the user to an error-catching page if there is no data.

@each('task.single', $tasks, 'task')
@each('task.single', $tasks, 'task', 'task.nodata')

@forelse

This loop directive validates if there is data in a collection before printing it out.

@forelse ($sales as $sale)
    <div>{{ $sale->salesperson }}</div>
@empty
    <p>There is no sale</p>
@endforelse

@json

The @json directive accepts the same arguments as PHP’s json_encode function.

<script>
    var data = @json($array);
    var data = @json($array, JSON_PRETTY_PRINT);
</script>

It is recommended to only use the @json directive to render existing variables as JSON.

@isset & @ empty

Developers don’t often use these 2 directives alone, then tend to wrap them with the @if directive in order to determine whether a variable exists or not. Actually, we don’t need the @if to use them for condition checking.

@isset($books)
    Loop books here
@endisset

@empty($books)
    There is no book.
@endempty

@verbatim

We use @ symbol before a curly brace to inform Blade to avoid rendering that variable that should be used by other JavaScript frameworks. Blade provides the @verbatim directive, which can be used if you are using JavaScript variables in a large portion of your template.

@verbatim
    <div class="my-wrapper">
        Task: {{ task_name }}.
    </div>
@endverbatim

@php

The @php directive allows embedding PHP code into your views.

@php
    $a = 2;
    $b = $a * 10;
@endphp

@push & @stack

Blade allows developers to push to named stacks which can be rendered somewhere else in another view or layout. 

@push('scripts')
    <script src="/custom-script.js"></script>
@endpush
<head>
    <!-- Head Contents -->
    @stack('scripts')
</head>

@hasSection

The @hasSection directive determines if a template inheritance section has content.

@hasSection('footer-widgets')
    <div class="pull-right">
        @yield('footer-widgets')
    </div>
@endif

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top