Home » Check If Array is Empty in Blade using Laravel

Check If Array is Empty in Blade using Laravel

by Online Tutorials Library

Check If Array is Empty in Blade using Laravel

In this section, we are going to learn about whether an array is empty or not in Blade. We will use Laravel Blade to do this. We can perform it in various versions of Laravel applications like Laravel 6, 7, and 8.

In our below example, we will see the different functions to check an array’s emptiness in blade. Sometimes the unexpected output or software crashes is occurred by the empty array. If we want to avoid this type of situation, we have to check whether the given or defined array in the blade is empty or not beforehand. 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:

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. But in our example, we will instead of using foreach loop inside an if statement, we will use the forelse blade template. When we execute the program using the foreach or forelse, both will generate the same result, but we can easily read the forelse loop, and it will contain less amount of code as compared to the foreach loop.

Controller Code:

Blade Code:

Example 2:

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:

Blade Code:

Example 3:

In the below example, we will use @if empty() to examine the array in Laravel.

Controller Code:

Blade Code:

Example 4:

In the below example, we will use @if count() to examine the array in Laravel.

Controller Code:

Blade Code:

Now our above code is ready to run. When we run this, the following output will be generated:

Check If Array is Empty in Blade using Laravel


You may also like