How to use Blade templates in Laravel
The Laravel view files that end with .blade.php
and are Blade templates.
Blade is a server-side templating language.
In its basic form it’s HTML. As you can see, those templates I used above don’t have anything other than HTML.
But you can do lots of interesting stuff in Blade templates: insert data, add conditionals, do loops, display something if the user is authenticated or not, or show different information depending on the environment variables (e.g. if it’s in production or development), and much more.
Here’s a 101 on Blade (for more I highly recommend the official Blade guide).
In the route definition, you can pass data to a Blade template:
Route::get('/test', function () {
return view('test', ['name' => 'Flavio']);
});
and use it like this:
<h1>{{ $name }}</h1>
The {{ }}
syntax allows you to add any data to the template, escaped.
Inside it you can also run any PHP function you like, and Blade will display the return value of that execution.
You can comment using {{-- --}}
:
{{-- <h1>test</h1> --}}
Conditionals are done using @if
@else
@endif
:
@if (name === 'Flavio')
<h1>Yo {{ $name }}</h1>
@else
<h1>Good morning {{ $name }}</h1>
@endif
There’s also @elseif
, @unless
which let you do more complex conditional structures.
We also have @switch
to show different things based on the result of a variable.
Then we have shortcuts for common operations, convenient to use:
@isset
shows a block if the argument is defined@empty
shows a block if an array does not contain any element@auth
shows a block if the user is authenticated@guest
shows a block if the user is not authenticated@production
shows a block if the environment is a production environment
Using the @php
directive we can write any PHP:
@php
$cats = array("Fluffy", "Mittens", "Whiskers", "Felix");
@endphp
We can do loops using these different directives
@for
@foreach
@while
Like this:
@for ($i = 0; $i < 10; $i++)
Count: {{ $i }}
@endfor
<ul>
@foreach ($cats as $cat)
<li>{{ $cat }}</li>
@endforeach
</ul>
Like in most programming languages, we have directives to play with loops like @continue
and @break
.
Inside a loop a very convenient $loop
variable is always available to tell us information about the loop, for example if it’s the first iteration or the last, if it’s even or odd, how many iterations were done and how many are left.
This is just a basic intro.
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025