In this post, I will explain how to remove an item by value in a Laravel collection. You will learn Laravel collection remove item by value using different methods. This will help you understand the different method to remove items from collections based on their value.
Methods to Remove Item by Value in Laravel Collection
We will explore multiple methods to remove an item by value from a collection:
- Using
reject()
Method to Remove Item by Value - Using
filter()
Method to Remove Item by Value
Laravel collection remove item by value step
Step 1: Using reject() Method to Remove Item by Value
The reject() method in a Laravel collection is used to filter out elements that match a specific condition. It returns a new collection that contains all the elements that do not meet the condition.
Example
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index() {
$collection = collect(['red', 'blue', 'green']);
$removeValue = 'blue';
$filteredCollection = $collection->reject(function ($item) use ($removeValue) {
return $item === $removeValue;
});
dd($filteredCollection->toArray());
}
}
Explanation:
- In this example, the reject() method is used to remove the item with value blue from the collection.
- The resulting collection contains all items except for blue.
Output:
array:2 [
0 => "red",
2 => "green",
]
2. Using filter() method to remove item by value
The filter() method retains items that match the condition in the callback.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DemoController extends Controller
{
public function index() {
$collection = collect(['red', 'blue', 'green']);
$removeValue = 'blue';
$filteredCollection = $collection->filter(function ($item) use ($removeValue) {
return $item !== $removeValue;
});
dd($filteredCollection->toArray());
}
}
Explanation:
- The callback determines which items to include.
- Item the match are removed.
Output:
array:2 [
0 => "red",
2 => "green",
]
I hope this tutorial help you.