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...
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him