transform() ใน Laravel Collections: แปลงข้อมูลในตัวเอง

transform() ใน Laravel Collections: แปลงข้อมูลในตัวเอง

ปัญหา / บทนำ

เมื่อเขียนโค้ด Laravel มักพบว่าต้องการปรับเปลี่ยนข้อมูลใน collection ให้เป็นรูปแบบที่ต้องการ แต่ map() จะ return ให้ collection ใหม่ ซึ่งอาจทำให้ใช้ memory มากเกินไป วิธีแก้ปัญหาคือใช้ transform() ที่แปลงข้อมูลในตัวเอง!

🔧 วิธีใช้งาน

3.1 พื้นฐาน transform()

// เริ่มต้น
$collection = collect(['apple', 'banana', 'orange']);

// แปลงข้อมูลในตัวเอง
$collection->transform(function ($item, $key) {
    return 'fruit_' . $item;
});

// ผลลัพธ์: ['fruit_apple', 'fruit_banana', 'fruit_orange']
// โดยที่ collection เดิมถูกแก้ไขไปแล้ว

3.2 แตกต่างจาก map()

// map() คือคืนค่า collection ใหม่
$original = collect([1, 2, 3]);
$new = $original->map(function ($item) {
    return $item * 2;
});
// $original: [1, 2, 3] (ไม่เปลี่ยน)
// $new: [2, 4, 6] (collection ใหม่)

// transform() คือแก้ในตัวเอง
$collection = collect([1, 2, 3]);
$collection->transform(function ($item) {
    return $item * 2;
});
// $collection: [2, 4, 6] (ถูกแก้ไข)

3.3 ใช้งานจริงกับข้อมูลจริง

// แปลงข้อมูลจาก API response
$users = collect([
    ['id' => 1, 'name' => 'John', 'age' => 25],
    ['id' => 2, 'name' => 'Jane', 'age' => 30],
]);

$users->transform(function ($user) {
    return [
        'user_id' => $user['id'],
        'display_name' => 'User: ' . $user['name'],
        'age_group' => $user['age'] < 30 ? 'young' : 'senior',
        'profile_url' => '/users/' . $user['id']
    ];
});

📌 ตัวอย่างใช้งานจริง

4.1 การประมวลผล API Response

// รับจาก API แล้วปรับเปลี่ยนก่อนส่งให้ frontend
$response = collect($apiData)
    ->transform(function ($item) {
        return [
            'id' => $item['id'],
            'name' => htmlspecialchars($item['name']),
            'created_at' => Carbon::parse($item['created_at'])->format('d/m/Y'),
            'status_badge' => $item['active'] ? 'Active' : 'Inactive'
        ];
    });

4.2 การประมวลผลข้อมูลจาก Database

// ปรับรูปแบบข้อมูลจาก database ให้เหมาะสำหรับ report
$orders = Order::all()->transform(function ($order) {
    return [
        'order_id' => $order->id,
        'customer_name' => $order->customer->name,
        'total_amount' => number_format($order->total, 2),
        'days_ago' => $order->created_at->diffInDays()
    ];
});

4.3 การคำนวณฟิลด์ใหม่

// เพิ่มฟิลด์คำนวณจากข้อมูลเดิม
$products = collect([
    ['name' => 'Laptop', 'price' => 25000, 'stock' => 10],
    ['name' => 'Phone', 'price' => 15000, 'stock' => 5],
]);

$products->transform(function ($product) {
    return [
        'name' => $product['name'],
        'price' => $product['price'],
        'stock' => $product['stock'],
        'total_value' => $product['price'] * $product['stock'],
        'is_low_stock' => $product['stock'] < 10
    ];
});

📌 สรุป

  • transform() คือ method ที่แปลงข้อมูลใน collection เดิม (in-place)
  • ✅ ใช้งานง่ายกว่า map() + forget() หากต้องการแก้ในตัวเอง
  • ✅ ประหยัด memory และ performance สำหรับข้อมูลขนาดใหญ่
  • ✅ ต้อง return ค่าใหม่ทุกครั้งที่มีการแปลง
  • ❌ ต้องระวังการไม่ return ค่าอาจทำให้ตัวข้อมูลกลายเป็น null
  • 🎯 เหมาะสำหรับ: การประมวลผลข้อมูลที่ต้องการแก้ไขเฉพาะตัวเดิม

Laravel Collections transform() method

เกี่ยวกับผู้เขียน

ITTHIPAT

สวัสดีครับผม อิทธิพัทธ์ (เป้) ชอบหาเทคนิคต่างๆที่ทำให้ชีวิต Programmer ง่ายขึ้น ทั้ง Automate, Library ชอบทำ Blog และ Video ถ้ามีเวลานะ!

ขอบคุณทุกคนที่ติดตาม และอ่านบทความของผมครับ ผมหวังว่าความรู้ที่เขียนขึ้นในเว็บไซต์นี้จะช่วยทุกท่านได้ไม่มากก็น้อย 

Scroll to Top