Join WhatsApp ChannelJoin Now

Remove Null and Empty Values In Laravel

Hi dev,

Today, i show you Remove Null and Empty Values In Laravel. In this article will tell you Remove Null and Empty Values In Laravel. you will Remove Null and Empty Values In Laravel. We will use the filter() method to remove null, false and empty values from the laravel collection. So, let’s see an example with output.

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

So, let’s follow few steps to create example of Remove Null and Empty Values In Laravel.

Example:

<?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 will assist you…

Recommended Posts