PHP
Extending Eloquent Collections with Custom Methods
Enhance your Eloquent collections by adding custom methods, allowing you to encapsulate complex logic and reuse it across multiple query results in Laravel applications.
<?php
namespace App\Collections;
use Illuminate\Database\Eloquent\Collection;
class UserCollection extends Collection
{
/**
* Get a comma-separated string of all user emails.
*
* @return string
*/
public function getEmailsString(): string
{
return $this->implode('email', ', ');
}
/**
* Filter users by active status and return only their names.
*
* @return \Illuminate\Support\Collection
*/
public function activeUserNames()
{
return $this->filter(function ($user) {
return $user->is_active;
})->pluck('name');
}
}
// In your User Model:
// use App\Collections\UserCollection;
// class User extends Model
// {
// public function newCollection(array $models = []): UserCollection
// {
// return new UserCollection($models);
// }
// }
// Usage example in a controller:
// $activeUsers = User::where('created_at', '>', now()->subMonth())->get();
// $emails = $activeUsers->getEmailsString(); // '[email protected], [email protected]'
// $activeNames = $activeUsers->activeUserNames(); // ['User One', 'User Two']
How it works: By default, Eloquent returns collections of models as `Illuminate\Database\Eloquent\Collection`. You can extend this class to add your own custom methods, encapsulating common business logic directly onto the collection objects. This snippet shows how to create a `UserCollection` with methods like `getEmailsString()` and `activeUserNames()`. By overriding the `newCollection()` method in your `User` model, you ensure that all results for `User` models are returned as instances of your custom collection, making your code more expressive and reusable.