Laravel Collections where() Method: คู่มือฉบับสมบูรณ์

Laravel Collections where() Method: คู่มือฉบับสมบูรณ์

สวัสดีครับนักพัฒนา Laravel ทุกท่าน! วันนี้เราจะมาพูดถึงหนึ่งใน methods ที่ใช้บ่อยที่สุดของ Laravel Collections นั่นคือ where() method กันครับ

บทนำ – Laravel Collections where() คืออะไร?

Laravel Collections เป็น class ที่ช่วยให้เราจัดการกับ arrays ได้อย่างมีประสิทธิภาพและง่ายดาย โดย where() method เป็นหัวใจสำคัญในการกรองข้อมูล (filtering) จาก collection ตามเงื่อนไขที่เรากำหนด

ทำไมต้องใช้ where() ในการกรองข้อมูล

ลองนึกภาพว่าคุณมีข้อมูล users หลายพันรายการ และต้องการกรองเฉพาะ users ที่มี status เป็น ‘active’ หรือต้องการหา products ที่มีราคาในช่วงที่กำหนด นี่คือจุดที่ where() method ทำให้ชีวิตเราง่ายขึ้นมาก

$users = collect([
    ['name' => 'John', 'status' => 'active'],
    ['name' => 'Jane', 'status' => 'inactive'],
    ['name' => 'Bob', 'status' => 'active'],
]);

$activeUsers = $users->where('status', 'active');

ข้อดีของการใช้ Collection methods แทน loop

  • โค้ดกระชับ – เขียนน้อยลง อ่านง่ายขึ้น
  • Method chaining – สามารถต่อ methods กันได้เรื่อยๆ
  • Functional programming – เขียนโค้ดแบบ declarative แทน imperative
  • Built-in optimizations – Laravel ดูแล performance ให้เรา

Basic Syntax – รูปแบบการใช้งาน where()

รูปแบบพื้นฐาน

where($key, $operator, $value)

Parameters:
$key – ชื่อ key ที่ต้องการเช็คในแต่ละ item
$operator – operator สำหรับเปรียบเทียบ (optional)
$value – ค่าที่ต้องการเปรียบเทียบ (optional)

Laravel Collections where() method ตัวอย่างโค้ดพื้นฐานใน terminal style

Comparison Operators ที่รองรับ

Laravel Collections where() รองรับ operators หลายแบบ:

Operatorความหมาย
= หรือ ==เท่ากับ
!= หรือ <>ไม่เท่ากับ
<น้อยกว่า
>มากกว่า
<=น้อยกว่าหรือเท่ากับ
>=มากกว่าหรือเท่ากับ
likeเหมือน pattern (SQL LIKE)

Loose vs Strict Comparison

  • where() – ใช้ loose comparison (PHP ==) – ค่า '1' กับ 1 ถือว่าเท่ากัน
  • whereStrict() – ใช้ strict comparison (PHP ===) – ค่า '1' กับ 1 ถือว่าไม่เท่ากัน

ตัวอย่างการใช้งาน where() แบบต่างๆ

Example 1 – where() แบบ Simple Match

การใช้งานพื้นฐานที่สุด คือการเช็คว่าค่าเท่ากับ what we’re looking for:

$collection = collect([
    ['name' => 'John', 'status' => 'active'],
    ['name' => 'Jane', 'status' => 'inactive'],
    ['name' => 'Bob', 'status' => 'active'],
    ['name' => 'Alice', 'status' => 'pending'],
]);

$active = $collection->where('status', 'active');

// Result:
// [
//     ['name' => 'John', 'status' => 'active'],
//     ['name' => 'Bob', 'status' => 'active'],
// ]

Example 2 – where() กับ Operator

เราสามารถใช้ operators ต่างๆ ในการเปรียบเทียบได้:

$products = collect([
    ['name' => 'Product A', 'price' => 100],
    ['name' => 'Product B', 'price' => 250],
    ['name' => 'Product C', 'price' => 500],
    ['name' => 'Product D', 'price' => 50],
]);

// หาสินค้าราคา 200 ขึ้นไป
$expensive = $products->where('price', '>=', 200);
// Result: Product B (250), Product C (500)

// หาสินค้าราคาไม่ถึง 100
$cheap = $products->where('price', '<', 100);
// Result: Product D (50)

Example 3 – where() กับ Callback/Closure

สำหรับเงื่อนไขที่ซับซ้อน เราสามารถใช้ callback ได้:

$users = collect([
    ['name' => 'John', 'age' => 25, 'role' => 'user'],
    ['name' => 'Jane', 'age' => 17, 'role' => 'user'],
    ['name' => 'Bob', 'age' => 30, 'role' => 'admin'],
]);

$adults = $users->where(function ($user) {
    return $user['age'] >= 18;
});

$admins = $users->where(function ($user) {
    return $user['role'] === 'admin' && $user['age'] >= 20;
});

Example 4 – where() แบบไม่ระบุ value (truthy check)

ถ้าเราไม่ระบุ value ตัว where() จะเช็คว่าค่านั้นเป็น truthy (ไม่ null, ไม่ false, ไม่ 0, ไม่ empty string):

$collection = collect([
    ['name' => 'John', 'is_active' => true],
    ['name' => 'Jane', 'is_active' => false],
    ['name' => 'Bob', 'is_active' => true],
    ['name' => 'Alice', 'is_active' => null],
]);

$active = $collection->where('is_active');
// Result: John และ Bob (เพราะ true เป็น truthy)
เปรียบเทียบ where vs whereStrict vs whereIn ใน Laravel Collections

Related Methods – Methods ที่เกี่ยวข้องกับ where()

Laravel Collections มี methods อื่นๆ ที่เกี่ยวข้องกับการกรองข้อมูลมากมาย:

whereIn() – กรองด้วย array ของค่า

$collection = collect([
    ['product' => 'Apple', 'category' => 'fruit'],
    ['product' => 'Carrot', 'category' => 'vegetable'],
    ['product' => 'Banana', 'category' => 'fruit'],
    ['product' => 'Potato', 'category' => 'vegetable'],
]);

$fruits = $collection->whereIn('category', ['fruit']);
// Result: Apple, Banana

whereInStrict() – whereIn แบบ strict comparison

// ความแตกต่างระหว่าง whereIn และ whereInStrict
$collection = collect([
    ['id' => 1],
    ['id' => '1'],  // string
    ['id' => 2],
]);

$whereIn = $collection->whereIn('id', [1]);     // จะเจอ 2 items (1 และ '1')
$whereInStrict = $collection->whereInStrict('id', [1]); // จะเจอ 1 item (int 1 เท่านั้น)

whereNotIn() – กรองออกด้วย array ของค่า

$collection = collect([
    ['name' => 'John', 'role' => 'admin'],
    ['name' => 'Jane', 'role' => 'user'],
    ['name' => 'Bob', 'role' => 'moderator'],
]);

$notAdmin = $collection->whereNotIn('role', ['admin']);
// Result: Jane, Bob

whereBetween() – กรองด้วยช่วงของค่า

$products = collect([
    ['name' => 'A', 'price' => 50],
    ['name' => 'B', 'price' => 150],
    ['name' => 'C', 'price' => 300],
    ['name' => 'D', 'price' => 500],
]);

$inRange = $products->whereBetween('price', [100, 400]);
// Result: B (150), C (300)

whereNotBetween() – กรองออกด้วยช่วงของค่า

$outOfRange = $products->whereNotBetween('price', [100, 400]);
// Result: A (50), D (500)

whereNull() / whereNotNull() – กรองค่า null

$users = collect([
    ['name' => 'John', 'email_verified_at' => '2024-01-01'],
    ['name' => 'Jane', 'email_verified_at' => null],
    ['name' => 'Bob', 'email_verified_at' => '2024-02-01'],
]);

$verified = $users->whereNotNull('email_verified_at');
// Result: John, Bob

$unverified = $users->whereNull('email_verified_at');
// Result: Jane

whereStrict() – comparison แบบ ===

$collection = collect([
    ['id' => 1],
    ['id' => '1'],
    ['id' => 2],
]);

$strict = $collection->whereStrict('id', 1);
// Result: เฉพาะ item ที่มี id === 1 (int) เท่านั้น
Laravel Collections method chaining ตัวอย่างการกรอง users

Real-world Use Cases – การใช้งานจริง

กรอง users ตาม status และ role

$users = collect($usersArray);

$activeAdmins = $users
    ->where('status', 'active')
    ->where('role', 'admin')
    ->sortBy('name')
    ->values();

// หรือใช้ whereIn สำหรับหลาย roles
$activeStaff = $users
    ->where('status', 'active')
    ->whereIn('role', ['admin', 'moderator', 'editor'])
    ->sortByDesc('created_at')
    ->take(10);

กรอง products ตามราคาและ category

$products = collect($productsFromAPI);

$affordableElectronics = $products
    ->where('category', 'electronics')
    ->whereBetween('price', [500, 5000])
    ->where('in_stock', true)
    ->sortBy('price')
    ->values();

Chaining กับ methods อื่นๆ

พลังที่แท้จริงของ Collections คือการ chain methods ต่างๆ:

$result = collect($data)
    ->where('status', 'published')
    ->where('views', '>=', 1000)
    ->whereBetween('created_at', [
        now()->subMonth()->startOfDay(),
        now()->endOfDay()
    ])
    ->sortByDesc('views')
    ->take(5)
    ->map(fn ($item) => [
        'title' => $item['title'],
        'views' => $item['views'],
    ])
    ->values();

// หรือใช้ firstWhere() สำหรับหา item แรกที่ตรงเงื่อนไข
$firstExpensive = $products->firstWhere('price', '>=', 1000);

Tips & Best Practices

การใช้ where() กับ Eloquent Collection

เมื่อคุณดึงข้อมูลจาก database ด้วย Eloquent คุณจะได้ Eloquent Collection ซึ่งมี methods เหมือน Collection ปกติ:

$users = User::where('status', 'active')
    ->where('role', 'admin')
    ->get();

// แต่ถ้าต้องการกรองเพิ่มเติมใน memory
$recentAdmins = $users
    ->where('created_at', '>=', now()->subWeek())
    ->sortByDesc('created_at');

Performance Considerations

  • ใช้ where() ก่อน sortBy() – กรองข้อมูลก่อนจะช่วยลดจำนวน items ที่ต้อง sort
  • ใช้ values() หลัง filter – เพื่อ reset keys ให้เป็น 0, 1, 2…
  • ถ้าข้อมูลเยอะมาก – พิจารณาใช้ database query แทน collection methods
// ❌ ไม่ดี - sort ก่อน filter
$slow = $collection->sortBy('price')->where('price', '>=', 100);

// ✅ ดี - filter ก่อน sort
$fast = $collection->where('price', '>=', 100)->sortBy('price');

การ chain methods อย่างถูกต้อง

// Chain methods อย่างเป็นระเบียบ
$filtered = collect($items)
    ->where('active', true)                    // 1. กรองก่อน
    ->whereIn('category', $categories)        // 2. กรองเพิ่ม
    ->sortBy('name')                           // 3. เรียงลำดับ
    ->map(fn ($item) => $item['name'])         // 4. transform
    ->values();                                // 5. reset keys

สรุป

where() method เป็นหนึ่งใน tools ที่สำคัญที่สุดใน Laravel Collections ช่วยให้เราสามารถกรองข้อมูลได้อย่างยืดหยุ่นและมีประสิทธิภาพ ไม่ว่าจะเป็น:

  • การเปรียบเทียบแบบง่ายๆ ด้วย where()
  • การกรองด้วย array ด้วย whereIn()
  • การกรองด้วยช่วงด้วย whereBetween()
  • การกรอง null values ด้วย whereNull()/whereNotNull()

การเข้าใจวิธีใช้งาน methods เหล่านี้จะช่วยให้โค้ดของคุณสะอาดและอ่านง่ายขึ้นมาก

หากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับ Laravel Collections methods อื่นๆ สามารถติดตามบทความต่อไปได้เลยครับ!


Tags: Laravel, PHP, Laravel Collections, Tutorial

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

ITTHIPAT

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

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

Scroll to Top