Laravel Collection get() Method วิธีดึงข้อมูลตาม Key
บทนำ
เมื่อทำงานกับ Laravel Collections บางครั้งเราต้องการดึงข้อมูลเฉพาะเจาะจงจาก Collection โดยอาศัย key ของ element นั้นๆ method get() จะช่วยให้คุณทำได้ง่ายและสะดวก
วิธีใช้งาน
Basic Usage
$collection = collect([
'name' => 'John',
'age' => 30,
'city' => 'Bangkok'
]);
// ดึงค่าตาม key
$name = $collection->get('name'); // 'John'
$age = $collection->get('age'); // 30
การใช้ Default Value
ถ้า key ไม่มีอยู่จริง สามารถกำหนดค่าเริ่มต้นได้:
$collection = collect(['name' => 'John']);
// ใช้ค่า default
$country = $collection->get('country', 'Thailand'); // 'Thailand'
// หรือใช้ Closure
$country = $collection->get('country', function() {
return 'Default Country';
});
ดึงหลาย Keys พร้อมกัน
$data = collect([
'name' => 'John',
'age' => 30,
'city' => 'Bangkok',
'country' => 'Thailand'
]);
// ดึงเฉพาะบาง keys
$subset = $data->only(['name', 'city']);
// ['name' => 'John', 'city' => 'Bangkok']
ตัวอย่างใช้งานจริง
ดึงข้อมูลจาก API Response
$apiResponse = collect($response->json());
$userId = $apiResponse->get('user.id');
$userName = $apiResponse->get('user.name', 'Guest');
$email = $apiResponse->get('user.email', '[email protected]');
กับ Array ของ Objects
$products = collect([
(object)['id' => 1, 'name' => 'iPhone', 'price' => 30000],
(object)['id' => 2, 'name' => 'Samsung', 'price' => 28000],
(object)['id' => 3, 'name' => 'OPPO', 'price' => 15000],
]);
// get() ใช้กับ numeric index ได้เช่นกัน
$firstProduct = $products->get(0); // (object)['id' => 1, ...]
$secondProduct = $products->get(1); // (object)['id' => 2, ...]
ตรวจสอบก่อนดึง
$collection = collect(['name' => 'John']);
// ตรวจสอบก่อนดึง
if ($collection->has('email')) {
$email = $collection->get('email');
} else {
$email = 'not provided';
}
สรุป
get(key)– ดึงค่าตาม keyget(key, default)– ดึงค่าพร้อมค่าเริ่มต้นget(key, closure)– ดึงค่าพร้อม Closure สำหรับค่า dynamiconly(keys)– ดึงเฉพาะ keys ที่ต้องการ
method get() เป็นพื้นฐานที่สำคัับสำหรับการเข้าถึงข้อมูลใน Collection โดยเฉพาะเมื่อต้องการจัดการกับ optional data ที่อาจไม่มีอยู่เสมอ