The 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:
{{ $name }}
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 {{-- --}}:
{{-- test --}}
Conditionals are done using @if @else @endif:
@if ($name === 'Flavio')
Yo {{ $name }}
@else
Good morning {{ $name }}
@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:
-
@issetshows a block if the argument is defined -
@emptyshows a block if an array does not contain any element -
@authshows a block if the user is authenticated -
@guestshows a block if the user is not authenticated -
@productionshows 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. We’ll see more about Blade with components later.