Skip to content

[12.x] Extends AsCollection to map through a closure #55611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

Diegslapasteque
Copy link

@Diegslapasteque Diegslapasteque commented Apr 30, 2025

Feature

The aim of this code is to be able to provide a closure to the $map parameter of the AsCollection::of() and AsCollection::using() methods, in order to be able to fully customize the creation of each item inside the collection.

public function casts(): array
{
    return [
        'collection' => AsCollection::of(function ($item) {
            // Custom logic here
        },
    ];
}

As casts needs to be serializable, I used the SerializableClosure in case a closure is used for the $map parameter.

I also extends this feature to the AsEncryptedCollection class:

public function casts(): array
{
    return [
        'collection' => AsEncryptedCollection::of(function ($item) {
            // Custom logic here
        },
    ];
}

Context

I want to use this new $map parameter (from the recent PR #55383) to generate a collection of data objects created with spatie/laravel-data, that are very well-suited for Eloquent casting. This is what I tried:

public function casts(): array
{
    return [
        'collection' => AsCollection::of([DataObject::class, 'from']),
    ];
}

To instantiate the data objects with the from() method, the Collection::map() method is used, which calls array_map([DataObject::class, 'from'], $array, $keys) internally. However, as the $keys are passed, the from() method thinks that these are properties of the DataObject, which is not.

With a closure, I would be able to do that to makes spatie/laravel-data objects works:

public function casts(): array
{
    return [
        'collection' => AsCollection::of(fn ($item) => DataObject::from($item)),
    ];
}

@Diegslapasteque Diegslapasteque changed the title [12.x] Extends AsCollection to map through a closure [12.x] Extends AsCollection to map through a closure Apr 30, 2025
@taylorotwell
Copy link
Member

I would suggest making a custom cast so we don't have to bother with serializable closures.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants