Skip to content

How to use Blade templates in Laravel

New Course Coming Soon:

Get Really Good at Git

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>
	<h1>Good morning {{ $name }}</h1>

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:

Using the @php directive we can write any PHP:

	$cats = array("Fluffy", "Mittens", "Whiskers", "Felix");

We can do loops using these different directives

Like this:

@for ($i = 0; $i < 10; $i++)
  Count: {{ $i }}

    @foreach ($cats as $cat)
        <li>{{ $cat }}</li>

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Laravel Handbook

Here is how can I help you: