Unpopular Laravel Blade Directives

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

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

@each

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

It can even send 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 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 @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 which 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 to embed PHP code into your views.

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

@push & @stack

Blade allows developer 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 *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close