Challenge 1: Render a List With Blade — Possible Solution
====================================================================
All Books
@if ($books->isEmpty())
No books in the catalog yet.
@else
@foreach ($books as $book)
- {{ $loop->iteration }}. {{ $book->title }}
@endforeach
@endif
use App\Models\Book;
public function index()
{
return view('books.index', ['books' => Book::all()]);
}
WHY THIS WORKS
--------------
- @if ($books->isEmpty()) checks Laravel's Collection isEmpty() method —
Book::all() returns an Eloquent Collection, not a plain array, so this
works the same way regardless of whether zero, one, or a thousand books
exist.
- $loop->iteration gives a 1-indexed count automatically inside the
@foreach, without the controller needing to pass any separate counter
variable into the view — directly analogous to Django's
forloop.counter from the equivalent DTL example.
- @else / @endif and @foreach / @endforeach must each be closed with
their matching end-directive — Blade compiles these down to real PHP
control structures, and a missing @endif or @endforeach produces a
genuine PHP parse error when the view is rendered, not a silently
broken page.