Laravel Blade Check Empty Array Example; In this tutorial, you will learn how to check if the array is empty in laravel blade when using the array member foreach.
This tutorial shows you how to check whether the array is empty or not null as well as how can use the foreach loop with empty data in laravel blade file. In order to check whether the array is empty or not in a blade, laravel provides various functions, and we are going to use them in our following example.
Example 1: Using @forelse @empty
In the below example, we will use @forelse and @empty to examine the array in Laravel. We can easily iterate our elements of collection by using the foreach loop.The laravel forelse loop, and will contain less amount of code as compared to the foreach loop.
In Controller
use App\Models\Post;
public function index()
{
$posts = Post::get();
return view('home',compact('posts '));
}
In Blade File
<div class="card-header">
<h4>Laravel Check Array Empty in Blade </h4>
</div>
<div class="card-body">
@forelse ($posts as $post)
<p>post list here</p>
@empty
<p>No post found</p>
@endforelse
</div>
Example 2:
In the below example, we will use @if count() to examine the array in Laravel.
Controller code:
use App\Models\Post;
public function index()
{
$posts = Post::get();
return view('home',compact('posts'));
}
Blade coce:
<div class="card-header">
<h4>Laravel Check Array Empty in Blade </h4>
</div>
<div class="card-body">
@if($posts->count())
<p>posts list with foreach here</p>
@else
<p>no posts found</p>
@endif
</div>
Example 3: @if empty()
In the below example, we will use @if empty() to examine the array in Laravel.
Controller Code:
use App\Models\Post;
public function index()
{
$posts = Post::get();
return view('home',compact('posts'));
}
Blade File Code:
<div class="card-header">
<h4> Laravel Check Array Empty in Blade </h4>
</div>
<div class="card-body">
@if(empty($posts))
<p>No posts found</p>
@else
<p>posts list here</p>
@endif
</div>
Example 4: using @empty
In the below example, we will use @empty to examine the array in Laravel. When we use an empty collection, it will require an additional if statement. It is necessary because we need to provide a valid message to the users.
Controller Code:
use App\Models\Post;
public function index()
{
$posts = Post::get();
return view('home',compact('posts'));
}
Blade File Code:
<div class="card-header">
<h4> Laravel Check Array Empty in Blade </h4>
</div>
<div class="card-body">
@empty($products)
<p>No posts found</p>
@else
<p>posts list here</p>
@endif
</div>
I hope these examples help you…