ItSolutionStuff.com

How to Remove Null and Empty Values from Laravel Collection?

By Hardik Savani • November 5, 2023
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...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Collection Remove First Item Example

Read Now →

How to Get Random Item from Laravel Collection?

Read Now →

How to Convert Collection to Array in Laravel?

Read Now →

Laravel Convert Collection to Array Example

Read Now →

How to Check If Collection is Empty in Laravel?

Read Now →

Laravel Collection map() Add Attribute Example

Read Now →

Laravel Collection keyBy() Method Example

Read Now →

Laravel Collection Implode Method Example

Read Now →

Laravel Collection Map Method Example

Read Now →

Laravel Collection Except() Method Example

Read Now →

Laravel Collection Duplicates Method Example

Read Now →

Laravel Collection Count and CountBy Method Example

Read Now →

Laravel Collection GroupBy with Examples

Read Now →

Laravel Collection SortByDesc Tutorial with Examples

Read Now →