How To Remove Null Empty Values From Laravel Collection

Reading Time: 2 minutes
96 Views

When working with data in Laravel Collections, you may encounter situations where you need to clean the Collection by removing null or empty values.

In this tutorial, we will guide you through the process of removing null and empty values from a Laravel Collection. Whether you’re a beginner or an experienced Laravel developer, this tutorial is designed to be accessible to all levels.

We will use filter() method to remove null, false, and empty values from laravel collection.

Read More: Laravel 10 Collection How To Remove First Item Example

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Example: Remove Null Empty Values From Laravel Collection

Here, is an example. Please check it,

<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
    
class PostController extends Controller
{
    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
)

That’s it.

We hope this article helped you to learn about How To Remove Null Empty Values From Laravel Collection Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more