PHP
Efficient Data Transformation with Eloquent Collections
Leverage powerful methods like `pluck`, `map`, and `filter` on Eloquent collections to efficiently transform, filter, and extract specific data from query results.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
}
// Example Data:
// User::all() might return a collection like:
// [
// { 'id': 1, 'name': 'Alice', 'email': '[email protected]', 'is_admin': true },
// { 'id': 2, 'name': 'Bob', 'email': '[email protected]', 'is_admin': false },
// { 'id': 3, 'name': 'Charlie', 'email': '[email protected]', 'is_admin': true },
// ]
// 1. Pluck specific columns:
// $emails = User::all()->pluck('email');
// // Result: ['[email protected]', '[email protected]', '[email protected]']
// $namesAndEmails = User::all()->pluck('email', 'name');
// // Result: ['Alice' => '[email protected]', 'Bob' => '[email protected]', 'Charlie' => '[email protected]']
// 2. Map over results to transform data:
// $transformedUsers = User::all()->map(function ($user) {
// return [
// 'user_id' => $user->id,
// 'full_name_email' => $user->name . ' (' . $user->email . ')',
// ];
// });
// // Result: Collection of arrays with 'user_id' and 'full_name_email'
// 3. Filter results:
// $adminUsers = User::all()->filter(function ($user) {
// return $user->is_admin;
// });
// // Result: Collection containing only Alice and Charlie
// 4. Combined operations:
// $adminEmails = User::all()
// ->filter(fn ($user) => $user->is_admin)
// ->pluck('email');
// // Result: ['[email protected]', '[email protected]']
How it works: Eloquent queries return `Illuminate\Database\Eloquent\Collection` instances, which extend Laravel's base `Collection` class. These collections provide a rich API for powerful and fluent data manipulation. Methods like `pluck()` extract specific column values, `map()` iterates and transforms each item, and `filter()` selects items based on a given condition. These methods allow for efficient in-memory data transformation without needing to requery the database.