How to Remove Null and Empty Values from Laravel Collection?
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection Remove First Item Example
- How to Get Random Item from Laravel Collection?
- How to Convert Collection to Array in Laravel?
- Laravel Convert Collection to Array Example
- How to Check If Collection is Empty in Laravel?
- Laravel Collection map() Add Attribute Example
- Laravel Collection keyBy() Method Example
- Laravel Collection Implode Method Example
- Laravel Collection Map Method Example
- Laravel Collection Except() Method Example
- Laravel Collection Duplicates Method Example
- Laravel Collection Count and CountBy Method Example
- Laravel Collection GroupBy with Examples
- Laravel Collection SortByDesc Tutorial with Examples