Type-safe collections based on Laravel Collections
gamez/typed-collection is a Laravel package for type-safe collections based on laravel collections.
It currently has 45 GitHub stars and 374.793 downloads on Packagist (latest version 8.0.0).
Install it with composer require gamez/typed-collection.
Discover more Laravel packages by gamez
or browse all Laravel packages to compare alternatives.
Last updated
[!NOTE]
Laravel 11 added theensure()collection method that verifies that all elements of a collection are of a given type or list of types. However, this verification does not prevent items of different types to be added at a later time.
[!NOTE]
If you use Laravel collections combined with Larastan/PHPStan, you won't need this library and can justâ„¢ annotate your collection classes directly.
The package can be installed with Composer:
$ composer require gamez/typed-collection
class Person
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
$taylor = new Person('Taylor');
$jeffrey = new Person('Jeffrey');
use Gamez\Illuminate\Support\TypedCollection;
/**
* @extends TypedCollection<array-key, Person>
*/
class People extends TypedCollection
{
protected static array $allowedTypes = [Person::class];
}
$people = People::make([$taylor, $jeffrey])
->each(function (Person $person) {
printf("This is %s.\n", $person->name);
});
/* Output:
This is Taylor.
This is Jeffrey.
*/
try {
People::make('Not a person');
} catch (InvalidArgumentException $e) {
echo $e->getMessage().PHP_EOL;
}
/* Output:
Output: A People collection only accepts items of the following type(s): Person.
*/
use Gamez\Illuminate\Support\LazyTypedCollection;
/**
* @extends LazyTypedCollection<array-key, Person>
*/
class LazyPeople extends LazyTypedCollection
{
protected static array $allowedTypes = [Person::class];
}
$lazyPeople = LazyPeople::make([$taylor, $jeffrey])
->each(function (Person $person) {
printf("This is %s.\n", $person->name);
});
/* Output:
This is Lazy Taylor.
This is Lazy Jeffrey.
*/
try {
LazyPeople::make('Nope!');
} catch (InvalidArgumentException $e) {
echo $e->getMessage().PHP_EOL;
}
/* Output:
Output: A People collection only accepts objects of the following type(s): Person.
*/
/**
* @extends LazyTypedCollection<array-key, int|string|Person>
*/
class MixedTypeCollection extends TypedCollection
{
protected static array $allowedTypes = ['int', 'string', Person::class];
}
Supported types are class strings, like Person::class, or types recognized by the
get_debug_type() function, int, float,
string, bool, and array.
The typedCollect() helper function enables you to dynamically create typed collections
on the fly:
$dateTimes = typedCollect([new DateTime(), new DateTime()], DateTimeInterface::class);
For further information on how to use Laravel Collections, have a look at the official documentation.