PHP

Create Custom Eloquent Collections with Helper Methods

Extend Laravel's default Eloquent collection to add domain-specific methods, simplifying data manipulation and business logic directly on model collections.

namespace App\Collections;

use Illuminate\Database\Eloquent\Collection;

class ProductCollection extends Collection
{
    public function onlyInStock()
    {
        return $this->filter(function ($product) {
            return $product->stock > 0;
        });
    }

    public function totalPrice()
    {
        return $this->sum(function ($product) {
            return $product->price * $product->quantity;
        });
    }
}

// In your Product model:
// use App\Collections\ProductCollection;
//
// class Product extends Model
// {
//     public function newCollection(array $models = [])
//     {
//         return new ProductCollection($models);
//     }
// }

// Example Usage:
$products = \App\Models\Product::all(); // Returns ProductCollection instance
$inStockProducts = $products->onlyInStock();
$totalOrderPrice = $products->totalPrice();
How it works: By default, Eloquent returns `Illuminate\Database\Eloquent\Collection` instances. This snippet shows how to create a custom collection (`ProductCollection`) by extending it and adding domain-specific methods like `onlyInStock()` or `totalPrice()`. You then instruct your model (`Product`) to use this custom collection via the `newCollection` method. This encapsulates related logic, making your code cleaner and more expressive when working with collections of models, promoting reusability and maintainability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs