Sử dụng Collection Get First và Last Item trong Laravel

Bài viết này mình sẽ chia sẻ cách sử dụng laravel collection để lấy phần tử đầu tiên và cuối cùng trong collection. Bạn có thể lấy bản ghi đầu tiên và cuối cùng từ collection trong laravel 6+ trở nên. Các bạn xem 2 ví dụ bên dưới để hiểu hơn nhé. Get First

Bài viết này mình sẽ chia sẻ cách sử dụng laravel collection để lấy phần tử đầu tiên và cuối cùng trong collection.
Bạn có thể lấy bản ghi đầu tiên và cuối cùng từ collection trong laravel 6+ trở nên.
Các bạn xem 2 ví dụ bên dưới để hiểu hơn nhé.

Get First Item:

Controller Code:

<?phpnamespaceAppHttpControllers;classItemControllerextendsController{/**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */publicfunctionindex(){$collection=collect([['id'=>1,'name'=>'One','email'=>'[email protected]'],['id'=>2,'name'=>'Two','email'=>'[email protected]'],['id'=>3,'name'=>'Three','email'=>'[email protected]'],['id'=>4,'name'=>'Four','email'=>'[email protected]']]);$first=$collection->first();dd($first);}}

Output:

array:3 [▼
  "id" => 1
  "name" => "One"
  "email" => "[email protected]"
]

Get Last Item:

Controller Code:

<?phpnamespaceAppHttpControllers;classItemControllerextendsController{/**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */publicfunctionindex(){$collection=collect([['id'=>1,'name'=>'One','email'=>'[email protected]'],['id'=>2,'name'=>'Two','email'=>'[email protected]'],['id'=>3,'name'=>'Three','email'=>'[email protected]'],['id'=>4,'name'=>'Four','email'=>'[email protected]']]);$last=$collection->last();dd($last);}}

Output:

array:3 [▼
  "id" => 4
  "name" => "Four"
  "email" => "[email protected]"
]

Hy vọng bài viết này giúp ích cho các bạn!

Nguồn: viblo.asia

Bài viết liên quan

Hướng Dẫn Đưa Bài Viết Lên Google AI Overviews Năm 2026 (Chuẩn SEO)

Tối ưu hóa cho AI Overviews (Tính năng tổng quan bằng AI của Google) là quá trình c

Có gì mới trong WordPress 7.0? Góc nhìn từ một thành viên cộng đồng

Những điểm nhấn quan trọng Chuẩn hóa tích hợp AI: WordPress® 7.0 ra mắt một khun

Cấu hình Prisma v7 Với Nest.js Mới nhất

Setup Prisma v7 trong Nest.js Bài viết dành cho ai mới học Nest.js và chọn prisma làm OR

Tấn Công Ứng Dụng Web: Mối Đe Dọa Hàng Đầu – Phần 2

viết lại nội dung này ” Phát hiện các cuộc tấn công Cross Site Scripting (XSS)