How to Check If Collection is Empty in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi Developer,

In this quick guide, we will teach you how to check if collection is empty laravel. It's a simple example of laravel collection check if empty. we will help you to give an example of check if empty collection laravel. if you want to see an example of check if collection is empty laravel blade then you are in the right place.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

There are several ways to check laravel collection is empty or not. I will give you the following list of examples that will check if the collection is empty in laravel.

Without further ago, please check the below examples code:

Example 1: Using isEmpty()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::get();

if (!$posts->isEmpty()) {

dd("posts eloquent collection is not empty.");

}else{

dd("posts eloquent collection is empty.");

}

}

}

Example 2: Using count()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::get();

if ($posts->count()) {

dd("posts eloquent collection is not empty.");

}else{

dd("posts eloquent collection is empty.");

}

}

}

Example 3: Using first()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::get();

if ($posts->first()) {

dd("posts eloquent collection is not empty.");

}else{

dd("posts eloquent collection is empty.");

}

}

}

Example 4: Using isNotEmpty()

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$posts = Post::get();

if ($posts->isNotEmpty()) {

dd("posts eloquent collection is not empty.");

}else{

dd("posts eloquent collection is empty.");

}

}

}

I hope it can help you...

Tags :
Shares