Skip to content

How to use Blade templates in Laravel

The Valley of Code

Your Web Development Manual

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.

→ Get my Laravel Handbook
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)