Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, I will give you a simple example of How to check Collection is Empty or Not in Laravel.
so you can easily use it with your laravel 5, laravel 6, laravel 7, and laravel 8 application. so let’s see bellow example below that will help you a lot.
At first, we write condition in the controller to Check Collection is Empty or Not in Laravel.
We have a products table in the database, let suppose if in the products table we have some data.
public function ListProduct(){
$productList = Product::get();
if($productList->count() == 0) {
return '<h2>No Product Found !</h2>';
}
else{
return '<h2>Product Found !</h2>';
}
return view('product.list',compact('productList'));
}
We have a Product Model, and we write conditions, We count all the product data, and the products table has some data, then the condition works like this.
Let’s delete or truncate the products table data, and see the output.
If the products table has no data, then the condition works like this.
Let’s write the code in the Blade file, to check collection is empty or not or if the model has data or not.
@if ($productList->count() > 0 )
@foreach($productList as $pkglist)
<h2>{{ $pkglist->name }}</h2>
<p>{{ $pkglist->description }}</p>
@endforeach
@else
<h2>No Product Found !</h2>
@endif
In this tutorial, we learned, How to Check Collection is Empty or Not in Laravel, in Controller, and in the Blade file.
I hope this article will help you with your Laravel application Project.