How to Check If Collection is Empty in 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 and laravel 9 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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

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…

Leave a Comment