Laravel Remove Null Value From the Collection

Nov 05, 2022 . Admin



Hello Friends,

This tutorial will provide an example of laravel removing null values from the collection. this example will help you how to remove a null element from a collection in laravel. you will learn how to remove null values from a collection in laravel. We will use laravel to remove a null item in a collection. follow the below step for the laravel collection to remove the null item example.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have just to follow the below step and you will get the layout as below:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Format Route web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RemoveNullController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/index',[RemoveNullController::class, 'index']);
Step 3: create RemoveNullController

we will create RemoveNullController. so you can see the below code with output:

php artisan make:controller RemoveNullController
App\Http\Controllers\RemoveNullController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RemoveNullController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    public function index()
    {
        $collection = collect(["Maxy", "Doe", null, "John", null, null, "Gadas"]);

        $newCollection= $collection->filter();

        dd($newCollection);

    }
}
Step 4: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/index
Output:
#items: array:4 [▼
    0 => "Maxy"
    1 => "Doe"
    3 => "John"
    6 => "Gadas"
]

I hope it can help you...

#Laravel