Shorter @foreach in Laravel Blade

One of the most common tasks when building Laravel applications is looping over data — like a list of users, posts, or comments. Blade, Laravel’s powerful templating engine, provides the @foreach directive for this purpose.

But did you know there are shorter and cleaner ways to write loops in Blade?

In this post, we’ll explore:

  • How @foreach works in Laravel
  • Alternatives and shorthand loop structures
  • The use of $loop variable for better control
  • Using components and @each for compact code
  • Real-world examples to clean up your Blade views

🔁 The Basics of @foreach in Laravel

In Laravel Blade, the traditional way to loop through a collection is:

@foreach ($users as $user)
    <p>{{ $user->name }}</p>
@endforeach

This works perfectly, but when your loops grow — especially with multiple nested conditions — things can get messy.

Let’s look at shorter and smarter alternatives.


✨ Shorthand 1: Use @each for Repetitive Templates

The @each directive allows you to loop through a collection and include a partial view for each item. It’s one of the cleanest ways to loop.

Syntax:

@each('partials.user', $users, 'user')

Breakdown:

  • 'partials.user' → the Blade partial for each item
  • $users → the collection to loop through
  • 'user' → the variable name passed into each partial

Example:

resources/views/partials/user.blade.php:

<li>{{ $user->name }}</li>

Usage:

<ul>
    @each('partials.user', $users, 'user')
</ul>

✅ Benefits:

  • Keeps your templates clean
  • No need to manually close the loop
  • Easier to reuse and test components

✨ Shorthand 2: Use Components in Loops

Laravel Blade components can make your loops cleaner and reusable.

Example:

Let’s say you have a Blade component named UserCard.

Component file: resources/views/components/user-card.blade.php

<div class="user-card">
    <h4>{{ $user->name }}</h4>
</div>

Usage:

@foreach ($users as $user)
    <x-user-card :user="$user" />
@endforeach

This makes your main template extremely readable:

<div class="user-list">
    @foreach ($users as $user)
        <x-user-card :user="$user" />
    @endforeach
</div>

📦 Bonus: Inline Loops for Simple Output

If you just want to output a list inline (like tags or comma-separated values), use regular PHP-style code:

{{ implode(', ', $tags->pluck('name')->toArray()) }}

Or:

@foreach ($tags as $tag)
    {{ $tag->name }}{{ !$loop->last ? ',' : '' }}
@endforeach

🧠 Using $loop in Blade

Inside any @foreach loop, Laravel gives you access to a special $loop variable:

@foreach ($items as $item)
    {{ $loop->index }} – {{ $item->title }}
@endforeach

Useful $loop Properties:

PropertyDescription
$loop->index0-based index
$loop->iteration1-based index
$loop->firsttrue on the first iteration
$loop->lasttrue on the last iteration
$loop->countTotal number of items
$loop->remainingItems left after current one

Example:

@foreach ($products as $product)
    <div>
        <strong>{{ $loop->iteration }}.</strong> {{ $product->name }}
        @if ($loop->first)
            <span class="badge">First Product</span>
        @endif
    </div>
@endforeach

✅ Comparison: Standard @foreach vs. @each

Feature@foreach@each
Verbose?Yes (needs loop open and close)No (compact, one-liner)
Readable?Good for inline logicBest for view separation
Use caseDynamic logic inside loopStatic layouts or cards
CleanlinessModerateVery clean

✍️ Practical Example

Let’s say you’re showing a list of blog posts:

🔴 Standard @foreach:

@foreach ($posts as $post)
    <div class="post">
        <h2>{{ $post->title }}</h2>
        <p>{{ Str::limit($post->body, 150) }}</p>
    </div>
@endforeach

🟢 Cleaner with @each:

@each('partials.post-card', $posts, 'post')

partials/post-card.blade.php:

<div class="post">
    <h2>{{ $post->title }}</h2>
    <p>{{ Str::limit($post->body, 150) }}</p>
</div>

🧼 Clean Code Tips for Blade Loops

  • ✅ Use @each when rendering repeatable layout blocks
  • ✅ Use Blade components with @foreach for better separation of logic
  • ✅ Avoid heavy logic inside Blade loops — move to controller or ViewModel
  • ✅ Use $loop variable for clean, conditionally styled output

🚫 Common Mistakes to Avoid

MistakeSolution
Writing logic-heavy loops in BladeMove logic to controller or partials
Forgetting to close @foreachAlways pair with @endforeach
Not using $loop->last for comma separationUse @if (!$loop->last) wisely
Writing duplicate code for each itemUse @each or components

🧾 Conclusion

Laravel gives you flexible and elegant ways to loop through data in Blade. While @foreach is the default and most powerful option, using shorter syntax like @each, Blade components, and the $loop variable can significantly improve your code readability and maintainability.

So the next time you write a Blade loop, ask yourself:

  • Can I turn this into a component?
  • Can I use @each for better separation?
  • Can I simplify logic using $loop helpers?

Smaller, cleaner Blade views mean faster development and easier maintenance. Embrace Laravel’s expressive syntax and let Blade do the heavy lifting!


Would you like a downloadable cheat sheet on all Blade directives including @foreach, @each, @auth, and more? Let me know and I’ll prepare one for you!


Leave a Reply

Your email address will not be published. Required fields are marked *