Laravel Find by value an Item in a Collection

10-Apr-2023

.

Admin

Laravel Find by value an Item in a Collection

Hello Friends,

In this tutorial, you will learn laravel to find the value of an item in a collection. let’s discuss laravel find by the value of the item from the collection. I want to share with you the laravel collection finds by value item example. it's a simple example of a laravel collection found by value item Code Example. Follow the below tutorial step on how to find by value an element from a collection in laravel.

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\FindByValueController;

/*

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

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

Step 3: create FindByValueController

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

php artisan make:controller FindByValueController

App\Http\Controllers\FindByValueController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FindByValueController extends Controller

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$collection = collect(['Doe',"John" ,"Gadas" ,"Maxy"]);

dd($collection->search(function($item, $key) {

$value = "John";

return $item == $value;

}));

}

}

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:

1 // app/Http/Controllers/FindByValueController.php:24

I hope it can help you...

#Laravel