DEV Community

Discussion on: Supercharge your Laravel 8 Collections

Collapse
 
bdelespierre profile image
Benjamin Delespierre

That's such a great idea.

Also I think it's worth noting that EloquentCollection can be specialized on a model basis like this:

class User extends Model
{
    public function newCollection(array $models = [])
    {
        return new UserCollection($models);
    }
}

class UserCollection extends Illuminate\Database\Eloquent\Collection
{
    public function admins(): self
    {
        return $this->filter($user => $user->isAdmin());
    }
}
Enter fullscreen mode Exit fullscreen mode

So you can do

User::all()->admins();
Enter fullscreen mode Exit fullscreen mode

(this example is purposefully oversimplified and in that specific case, one would better use scope...)