Simple way to tidy up your Blade views

A simple way to tidy up your Blade views!

Use the forelse loop, instead of a foreach loop nested in an if statement

1<!-- if/loop combination -->
2@if ($orders->count())
3 @foreach($orders as $order)
4 <div>
5 {{ $order->id }}
6 </div>
7 @endforeach
8@else
9 <p>You haven't placed any orders yet.</p>
10@endif
11 
12<!-- Forelse alternative -->
13@forelse($orders as $order)
14 <div>
15 {{ $order->id }}
16 </div>
17@empty
18 <p>You haven't placed any orders yet.</p>
19@endforelse

Tip given by @alexjgarrett

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord