PHP
Extend Eloquent Collections with Custom Macro Methods
Add custom, reusable functionality to your Laravel Eloquent collections by defining macro methods, streamlining common data manipulation tasks.
// In AppServiceProvider.php (or a dedicated service provider)
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Collection;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
//
}
public function boot(): void
{
// Define a macro to convert a collection to an associative array keyed by 'id'
Collection::macro('toAssocById', function () {
return $this->mapWithKeys(function ($item) {
return [$item['id'] => $item];
});
});
// Define another macro to filter a collection to only include active items
Collection::macro('activeOnly', function () {
return $this->filter(function ($item) {
return $item->is_active; // Assumes 'is_active' attribute or accessor exists
});
});
}
}
// Usage Example (e.g., in a controller or test)
use App\Models\User;
$users = User::all();
$usersById = $users->toAssocById(); // Returns a collection keyed by user IDs
foreach ($usersById as $id => $user) {
echo "User ID: $id, Name: {$user->name}
";
}
// Assuming a Post model with an 'is_active' attribute or accessor
use App\Models\Post;
$posts = Post::all();
$activePosts = $posts->activeOnly(); // Filters the collection to only active posts
foreach ($activePosts as $post) {
echo "Active Post: {$post->title}
";
}
How it works: Eloquent collections can be enhanced with custom methods by using `Collection::macro`. This example demonstrates how to add `toAssocById` to easily transform a collection into an associative array using item IDs as keys, and `activeOnly` to filter items based on an `is_active` property. This approach promotes clean, reusable, and domain-specific logic for manipulating your Eloquent collection data.