How to Remove Null and Empty Values from Laravel Collection?

By Hardik Savani November 5, 2023 Category : Laravel

Hi Friends,

This post will give you an example of laravel collection remove null values. Here you will learn laravel collection remove empty values. I would like to share with you how to remove empty value from laravel collection array. This post will give you a simple example of remove null values from collection laravel.

we will use filter() method to remove null, false, and empty values from laravel collection. so, let's see the simple example code with output:

In Laravel, the filter() method is used to filter the items in a collection based on a given callback function. This method is commonly used to iterate through a collection and keep only the items that meet a certain condition defined in the callback function. Here's how you can use the filter() method in Laravel:

Here's how you can use the filter() method in Laravel:

Example:

you can see the below controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$collection = collect([1, 2, null, 3, null, 4, '', false, 5]);

$collection = $collection->filter();

$collection = $collection->toArray();

dd($collection);

}

}

Output:

Array

(

[0] => 1

[1] => 2

[3] => 3

[5] => 4

[8] => 5

)

I hope it can help you...

Shares