Laravel Blade Conditions and Loops
A Blade directive is a Blade tag that adds logic to a view. Directives start with @ and add conditions and loops.
Return a view with data
The route passes a list of books and a count into the view.
Route::get('/books', fn () => view('books', ['books' => ['Dune', 'Foundation'], 'count' => 2]));Show a block by condition
A directive adds logic to a view, such as a condition or a loop.
@if ($count > 0)
<p>We have books.</p>
@else
<p>No books yet.</p>
@endifRepeat a block for each item
The loop prints one line for each book in the list.
@foreach ($books as $book)
<p>{{ $book }}</p>
@endforeachExample
Route::get('/books', fn () => view('books', ['books' => ['Dune', 'Foundation'], 'count' => 2]));
@if ($count > 0)
<p>We have books.</p>
@else
<p>No books yet.</p>
@endif
@foreach ($books as $book)
<p>{{ $book }}</p>
@endforeachKey points
- Blade directive: a Blade tag that starts with @ and adds logic to a view.
- Use @if to show a block only when a condition is true.
- Use @else for the block to show when the condition is false.
- Use @foreach to repeat a block for every item in a list.
In this example, the route passes a list of two books and a count of 2 into the books view. The @if block shows its line because the count is above 0. The @foreach block prints one line for each book. The page shows three lines.
Note
Every @if needs a matching @endif, and every @foreach needs a matching @endforeach.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @foreach do?