How to Remove a Null Element From a Collection in Laravel?




How to Remove a Null Element From a Collection in Laravel?

Hello Friends,

This example is focused on how to remove a null element from a collection in laravel. I explained simply about the laravel collection remove null item example. let’s discuss laravel collection to remove the null item Code Example. We will use laravel to remove a null item in a collection. Here, Creating a basic example of how to remove null values from a collection in laravel.

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



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



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();




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.



#items: array:4 [▼

0 => "Maxy"

1 => "Doe"

3 => "John"

6 => "Gadas"


I hope it can help you...