Blade Templates

Stacks

Blade allows you to push to named stacks which can be rendered in another view or layout.
Useful for javascript libraries required by child views

<!-- Add to the stack -->
@push('scripts')
    <script src="/example.js"></script>
@endpush

Render the stack

<head>
    <!-- Head Contents -->
    @stack('scripts')
</head>

Prepend to the beginning of a stack

@push('scripts')
    This will be second...
@endpush
// Later...
@prepend('scripts')
    This will be first...
@endprepend

Raw PHP

Execute a block of plain PHP

@php
    $counter = 1;
@endphp

Including Subviews

Include a Blade view from within another view.
All variables that are available to the parent view are also available to the included view

<div>
    <!-- resources/views/shared/errors/blade.php -->
    @include('shared.errors')
    <form>
        <!-- Form Contents -->
    </form>
</div>

Displaying Data

Blade's echo statements {{ }} are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. Display the contents of the name variable:

Hello, {{ $name }}.

Display results of a PHP function:

The current UNIX timestamp is {{ time() }}.

Display data without escaping with htmlspecialchars

Hello, {!! $name !!}.

Directives

#if Statements

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

#isset & empty

@isset($records)
    // $records is defined and is not null...
@endisset
@empty($records)
    // $records is "empty"...
@endempty

#Authentication

@auth
    // The user is authenticated...
@endauth
@guest
    // The user is not authenticated...
@endguest

#Loops

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor
@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach
@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse
@while (true)
    <p>I'm looping forever.</p>
@endwhile

Loop Iteration:

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif
    @if ($loop->last)
        This is the last iteration.
    @endif
    <p>This is user <!--swig7--></p>
@endforeach

See more: Laravel Loop Variable

Comments

{{-- This comment will not be present in the rendered HTML --}}
Comments