How to Display Lists Using foreach in Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
This article summarizes how to display lists using foreach in Laravel.
How to Use foreach
In a .blade.php
file, you can write:
<div>
<ol>
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ol>
</div>
The part between @foreach
and @endforeach
:
<li>{{ $user->name }}</li>
will be generated as many times as there are users in $users
.
Displaying Any Information for Each User
If you write various things between @foreach
and @endforeach
, that section will be generated for each user in $users
.
<div>
@foreach($users as $user)
<div>
<p>The user's name is {{ $user->name }}.</p>
<p>The ID is {{ $user->id }}.</p>
<img src="{{ $user->logo_url }}" alt="" />
</div>
@endforeach
</div>
You can freely use multiple tags, as long as you understand that the section between @foreach
and @endforeach
will be displayed as many times as there are users. You can also assign classes to tags and apply CSS.
Important Notes
Can Only Be Used in Blade Files
For example, if the output appears directly as:
@foreach($users as $user)
@endforeach
This might indicate that there is an error in the file name.
Incorrect: home.php
Correct: home.blade.php
This is a mistake that can happen a couple of times a year.
Mistakes with Closing Tags Can Be Catastrophic
Missing Closing Tag for div
<div>
@foreach($users as $user)
<div>
<p>The user's name is {{ $user->name }}.</p>
<p>The ID is {{ $user->id }}.</p>
<img src="{{ $user->logo_url }}" alt="" />
@endforeach
</div>
If you forget the closing </div>
, you will end up with a terrible layout because it will be missing as many times as there are users.
Missing Closing Tag for a (Catastrophic)
By the way, forgetting the closing tag for <a>
can be quite troublesome, as the browser automatically closes the tag in the output.
This might not show any visible issues, but you may notice oddities in spacing or hovering effects without understanding the cause.
@foreach($array as $a)
<div>
<a href="/">Home
</div>
@endforeach
Output:
<div><a href="/">Home</a></div>
<a href="/"></a>
<div><a href="/"></a><a href="/">Home</a></div>
<a href="/"></a>
<div><a href="/"></a><a href="/">Home</a></div>
<a href="/"></a>
If you have few elements, it's easy to spot, but in reality, you will often iterate over many tags with foreach
.
To avoid mistakes, it's best to keep your indentation neat and use a formatting plugin.
Summary
I have briefly summarized how to use foreach in Laravel Blade files.
I hope this is helpful to someone, including the important notes.
You can find more about this topic in the following resource: