Laravel Collection Remove Item by Value Example

By Hardik Savani November 5, 2023 Category : Laravel

Hi Dev,

This extensive guide will teach you laravel collection remove by value. I explained simply about how to remove item by value in laravel collection. you can see laravel collection delete by value. This post will give you a simple example of laravel collection remove item by value.

In this example, we will use reject() method to remove element by value in laravel collection.

The reject method in Laravel collections is used to filter a collection by excluding elements that match a specified condition. It returns a new collection containing all elements that do not meet the specified condition. Here's the basic syntax for using the reject method:

Here's how you can use the reject() method in Laravel:

Example 1:

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(['Hardik', 'Paresh', 'Mahesh', 'Rakesh']);

$valueToRemove = 'Rakesh';

$filteredCollection = $collection->reject(function ($item) use ($valueToRemove) {

return $item === $valueToRemove;

});

dd($filteredCollection->toArray());

}

}

Output:

Array

(

[0] => Hardik

[1] => Paresh

[2] => Mahesh

)

Example 2:

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([

['id' => 1, 'name' => 'Hardik', 'email' => 'hardik@gmail.com'],

['id' => 2, 'name' => 'Paresh', 'email' => 'paresh@gmail.com'],

['id' => 3, 'name' => 'Rakesh', 'email' => 'rakesh@gmail.com'],

]);

$valueToRemove = 'Paresh';

$filteredCollection = $collection->reject(function ($item) use ($valueToRemove) {

return $item['name'] === $valueToRemove;

});

dd($filteredCollection->toArray());

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

[email] => hardik@gmail.com

)

[2] => Array

(

[id] => 3

[name] => Rakesh

[email] => rakesh@gmail.com

)

)

I hope it can help you...

Shares