Collections in Laravel provide a powerful approach to modify data in your application. This tutorial will walk you through the process of removing items from a Laravel 10 Collection by value. This lesson is intended for all skill levels, whether you are a beginner or an experienced Laravel developer.
Collections frequently contain data that must be filtered or altered. The ability to delete objects by value is a valuable skill to have, whether you want to eliminate specific items that match a certain value or restructure your data.
We will use reject() method to remove element by value in laravel collection.
Read More: How To Remove Null Empty Values From Laravel Collection
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Example: Remove Item by Value From Laravel Collection
Here, is an example. Please check it,
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PostController extends Controller { public function index(Request $request) { $collection = collect(['Sanjay', 'Rakesh', 'Ashish', 'Vijay']); $valueToRemove = 'Rakesh'; $filteredCollection = $collection->reject(function ($item) use ($valueToRemove) { return $item === $valueToRemove; }); dd($filteredCollection->toArray()); } }
Output
Array
(
[0] => Sanjay
[1] => Ashish
[2] => Vijay
)
That’s it.
We hope this article helped you to learn about How To Remove Item by Value From Laravel Collection Tutorial in a very detailed way.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.