Home > Backend Development > PHP Tutorial > Collection Customization in Laravel Using CollectedBy

Collection Customization in Laravel Using CollectedBy

Emily Anne Brown
Release: 2025-03-06 02:17:09
Original
475 people have browsed it

Collection Customization in Laravel Using CollectedBy

Enhance Eloquent collection functionality with Laravel's CollectedBy attribute. This attribute offers a streamlined approach to customizing collections for specific model types, promoting cleaner, more maintainable code. Forget overriding the newCollection() method; CollectedBy provides a declarative solution at the class level.

Previously, tailoring model collections involved overriding the newCollection() method. This new attribute-based method offers a superior, class-level solution.

use Illuminate\Database\Eloquent\Attributes\CollectedBy;

#[CollectedBy(CustomCollection::class)]
class YourModel extends Model
{
    // Model implementation
}
Copy after login

Consider an e-commerce product catalog:

// Product Collection
<?php namespace App\Collections;

use Illuminate\Database\Eloquent\Collection;

class ProductCollection extends Collection
{
    public function inStock()
    {
        return $this->filter(fn($product) => $product->stock_count > 0);
    }

    public function onSale()
    {
        return $this->filter(fn($product) => $product->discount_percentage > 0);
    }

    public function byPriceRange($min, $max)
    {
        return $this->filter(function($product) use ($min, $max) {
            $price = $product->getEffectivePrice();
            return $price >= $min && $price <= $max;
        });
    }

    public function topRated()
    {
        return $this->filter(fn($product) => $product->average_rating >= 4)
            ->sortByDesc('average_rating');
    }
}

//Product model
namespace App\Models;

use App\Collections\ProductCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\CollectedBy;

#[CollectedBy(ProductCollection::class)]
class Product extends Model
{
    public function getEffectivePrice()
    {
        return $this->discount_percentage > 0 ? $this->price * (1 - $this->discount_percentage / 100) : $this->price;
    }
}
Copy after login

The CollectedBy attribute simplifies collection customization, resulting in cleaner, more readable Laravel applications.

The above is the detailed content of Collection Customization in Laravel Using CollectedBy. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template