In Laravel collections load many items, to find an element is too hard, so today I will show you how to use key item search the value in Laravel collection. By the example below help you to find item value by key in Laravel collection. I will give steps by step to explain about Laravel collection searching item by key. This is very short tutorial using a function to search an element data from collection. Anyway, the example below we can use with Laravel 6, Laravel 7, Laravel 8 and Laravel 9 as well.
Following step below to use a function in Laravel Collection to search item using key.
First step you have to download Laravel project to your computer, type following command to in your terminal to download the project.
composer create-project laravel/laravel Blog
Then we will have a controller file to implement short code by example code below. Let's run following command first to create a controller file
php artisan make:controller TestController
Open file app -> Http -> Controllers -> TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function index()
{
$items = collect(['fname' => 'Sok', 'lname' => "Sao" , 'address' => "Phnom Penh" , 'spouse' => "Pisey"]);
$value = $items ->get('address');
dd($value);
}
}
You will need to add route where your controller file located and the function should call.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
/*
|--------------------------------------------------------------------------
| 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('/', [TestController::class,'index']);
Now lastly, we will run following command to start server and launch new session in browser with following URL http://localhost:8000/
php artisan serve
Then launch your brower and to see the result.
"Phnom Penh"
Hope this article help you to find item in collection data. Have a nice day!
You may also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him