Get started with 33% off your first certification using code: 33OFFNEW

An introduction to Laravel's `@forelse`

2 min read
Published on 31st July 2023

When working with Laravel, you'll often find yourself dealing with collections or arrays of data. These collections are often displayed using loops in your Blade templates. Laravel offers the @foreach directive for looping over these collections, which is incredibly useful and widely used.

But what happens when the data set is empty? How do you handle this elegantly without having to write separate conditional checks for data existence? This is where Laravel's @forelse directive comes in.

What is the @forelse Directive?

The @forelse directive is a Blade construct provided by Laravel that combines the functionalities of @foreach and @if into a single, elegant solution.

The @forelse directive loops over an array or a collection of items similar to @foreach. However, it also checks if the data set is empty, and if it is, executes an @empty block.

The general syntax of @forelse is as follows:

@forelse ($items as $item)
    <!-- This block runs for each item in the collection -->
@empty
    <!-- This block runs when the collection is empty -->
@endforelse

When to Use @forelse?

You should consider using @forelse when you're dealing with a data set that may be empty and want to provide a default block of content for this case. For example, you may be displaying a list of blog posts, and want to show a message like "No posts found" when there are no posts to display.

Example of Using @forelse

Let's take a look at a practical example. Suppose we have a collection of blog posts that we want to display on a page:

@forelse ($posts as $post)
    <h2>{{ $post->title }}</h2>
    <p>{{ $post->excerpt }}</p>
@empty
    <p>No posts found.</p>
@endforelse

In this example, if the $posts collection has data, the loop will iterate over each post and display its title and excerpt. However, if the $posts collection is empty, it will display "No posts found."

You can also use it without the @empty clause:

@forelse ($posts as $post)
    <h2>{{ $post->title }}</h2>
    <p>{{ $post->excerpt }}</p>
@endforelse