Laravel Collection Find and Remove Item Example

10-Apr-2023

.

Admin

Laravel Collection Find and Remove Item Example

Hello Friends,

Now, let's see the post of the laravel collection find and remove item example. I explained step by step laravel finds and removes an item in a collection. This article will give you a simple example of how to find and remove an element from a collection in laravel. This article will implement a laravel collection to find items and remove them. follow the below step for the laravel collection to find and remove the item Code 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\FindRemoveController;

/*

|--------------------------------------------------------------------------

| 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',[FindRemoveController::class, 'index']);

Step 3: create FindRemoveController

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

php artisan make:controller FindRemoveController

App\Http\Controllers\FindRemoveController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FindRemoveController extends Controller

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$myCollection = collect(['a' => 0,'b' => 1,'c' => 2,'d' => 3 ,'e' => 4 ]);

$selector = ['c'];

$filtered = $myCollection->except($selector);

$filtered->all();

dd($filtered->all());

}

}

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:

array:4 [▼ // app/Http/Controllers/RemoveFirstController.php:23

"a" => 0

"b" => 1

"d" => 3

"e" => 4

]

I hope it can help you...

#Laravel