Filter an Illuminate collection with specifications.
You can support me by buying Pennant feature flags for Filament.
You can install the package via composer:
composer require maartenpaauw/laravel-specification-pattern
You can publish the config file with:
php artisan vendor:publish --tag="laravel-specification-pattern-config"
This is the contents of the published config file:
return [
'collection-method' => 'matching',
];
Here's how you can create a specification:
php artisan make:specification AdultSpecification
This will generate a specification class within the App\Specifications
namespace.
<?php
namespace App\Specifications;
use Maartenpaauw\Specifications\Specification;
/**
* @implements Specification<mixed>
*/
class AdultSpecification implements Specification
{
/**
* {@inheritDoc}
*/
public function isSatisfiedBy(mixed $candidate): bool
{
return true;
}
}
Imagine we have the following class which represents a person with a given age.
class Person {
public function __construct(public int $age)
{}
}
Let's apply the business logic:
<?php
namespace App\Specifications;
use Maartenpaauw\Specifications\Specification;
/**
- * @implements Specification<mixed>
+ * @implements Specification<Person>
*/
class AdultSpecification implements Specification
{
/**
* {@inheritDoc}
*/
public function isSatisfiedBy(mixed $candidate): bool
{
- return true;
+ return $candidate->age >= 18;
}
}
After applying the bussiness logic we can use the specification by directly calling the isSatisfiedBy
method or indirectly be filtering an eloquent collection by calling the matching
method.
$specification = new AdultSpecification();
// ...
$specification->isSatisfiedBy(new Person(16)); // false
$specification->isSatisfiedBy(new Person(32)); // true
$persons = collect([
new Person(10),
new Person(17),
new Person(18),
new Person(32),
]);
// ...
// Returns a collection with persons matching the specification
$persons = $persons->matching(new AdultSpecification());
// ...
$persons->count(); // 2
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.