PHPackages                             derheyne/laravel-collection-mapwithcast - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. derheyne/laravel-collection-mapwithcast

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

derheyne/laravel-collection-mapwithcast
=======================================

Automatically cast values in Laravel collections when using mapWithCast with typed closures.

v0.1(1y ago)3239[1 PRs](https://github.com/derheyne/laravel-collection-mapwithcast/pulls)MITPHPPHP ^8.3CI passing

Since Apr 13Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/derheyne/laravel-collection-mapwithcast)[ Packagist](https://packagist.org/packages/derheyne/laravel-collection-mapwithcast)[ Docs](https://github.com/derheyne/laravel-collection-mapwithcast)[ GitHub Sponsors](https://github.com/derheyne)[ RSS](/packages/derheyne-laravel-collection-mapwithcast/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (5)Used By (0)

Laravel Collection Macro: `mapWithCast`
=======================================

[](#laravel-collection-macro-mapwithcast)

[![GitHub Tests Action Status](https://camo.githubusercontent.com/1a19e3d68850d8022500332de34eeab276ec0c1c70d53f0f6b942319a465b399/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6465726865796e652f6c61726176656c2d636f6c6c656374696f6e2d6d617077697468636173742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/derheyne/laravel-collection-mapwithcast/actions?query=workflow%3Arun-tests+branch%3Amain)

Automatically cast values in Laravel collections when using `mapWithCast` with typed closures.

```
collect([['name' => 'John'], ['name' => 'Jane']])
    ->mapWithCast(fn (Fluent $data) => $data->name)

// Result: ['John', 'Jane']
```

📦 About
-------

[](#-about)

`mapWithCast` is a Laravel collection macro that enhances the map method by automatically casting each item in the collection to the type hinted in your closure. It saves you from manual casting and enforces better type safety, making your code cleaner and more expressive.

It supports both **scalar types** like `int` and `string` and complex Laravel-specific types like `Collection`, `Fluent`, and `Stringable`.

🚀 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require derheyne/laravel-collection-mapwithcast
```

The macro will be automatically registered thanks to Laravel's package discovery.

🧠 Type Support
--------------

[](#-type-support)

### ✅ Supported Types (Out of the Box)

[](#-supported-types-out-of-the-box)

- `int`
- `float`
- `bool`
- `string`
- `array`
- `object`
- `Illuminate\Support\Carbon` and `Carbon\Carbon`
- `Illuminate\Support\Collection`
- `Illuminate\Support\Fluent`
- `Illuminate\Support\Optional`
- `Illuminate\Support\Stringable`
- `Illuminate\Support\Uri`

### ⚙️ Extending with Custom Casters

[](#️-extending-with-custom-casters)

Need to handle your own types or custom logic? You can register additional casters by publishing the config file:

```
php artisan vendor:publish --tag=laravel-collection-mapwithcast-config
```

This will create a config file where you can specify your own custom casters:

```
// config/mapwithcast.php

return [
    'casters' => [
        App\Caster\SpatieLaravelDataCaster::class
    ],
];
```

```
namespace App\Casters;

use dhy\LaravelMapWithCastMacro\Contract\Caster;
use Spatie\LaravelData\Data;

class SpatieLaravelDataCaster implements Caster
{
    public function qualifies(mixed $type): bool
    {
        if (! is_string($type)) {
            return false;
        }

        return is_subclass_of(object_or_class: $type, class: Data::class, allow_string: true);
    }

    /** @param  Data  $type */
    public function cast(mixed $value, mixed $type): Data
    {
        return $type::from($value);
    }
}
```

Now you can automatically cast the value into the specified laravel-data DTO:

```
use Spatie\LaravelData\Data;

class CustomerData extends Data {
    public function __construct(
        public string $prename,
        public string $surname,
        public string $city,
    ) {}
}
collect([['prename' => 'Jane', 'surname' => 'Doe', 'city' => 'New York']])
    ->mapWithCast(fn (CustomerData $customer) => $customer->prename.' '.$customer->surname)

// Returns: ['Jane Doe']
```

📚 Examples
----------

[](#-examples)

### 🧮 Convert and Process Numbers

[](#-convert-and-process-numbers)

```
$totals = collect(['10.50', '20.75', '30'])
    ->mapWithCast(fn (float $price) => $price * 1.2);

// Result: [12.6, 24.9, 36.0]
```

### 🧠 Cast to Laravel `Collection`

[](#-cast-to-laravel-collection)

```
$sums = collect([[1, 2, 3], [4, 5, 6]])
    ->mapWithCast(fn (Collection $items) => $items->sum());

// Result: [6, 15]
```

### 🔄 Cast to Stringable

[](#-cast-to-stringable)

```
$slugs = collect(['Laravel Tips', 'PHP Tricks'])
    ->mapWithCast(fn (Stringable $str) => $str->slug());

// Result: ['laravel-tips', 'php-tricks']
```

### 🪡 Cast by specifying a custom caster

[](#-cast-by-specifying-a-custom-caster)

```
class CustomDataObject
{
    public function __construct(
        public string $value,
    ) {}
}

collect(['one', 'two', 'three'])
    ->mapWithCast(
        callback: fn (CustomDataObject $value) => 'Value: '.$value->value,
        caster: fn ($value, $type) => new $type($value),
    );

// Return ['Value: one', 'Value: two', 'Value: three']
```

### ✅ Testing

[](#-testing)

```
composer test
```

🧪 Compatibility
---------------

[](#-compatibility)

- Laravel 11.x, 12.x
- PHP 8.3+

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance72

Regular maintenance activity

Popularity19

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

395d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5128fff4560d34d46155b6bcefc1bf8680e24fbf2c75f61d712672790462f657?d=identicon)[dhy](/maintainers/dhy)

---

Top Contributors

[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")[![derheyne](https://avatars.githubusercontent.com/u/6844603?v=4)](https://github.com/derheyne "derheyne (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")

---

Tags

collectionlaravelmacrosphplaravelDaniel Heynelaravel-collection-mapwithcast

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/derheyne-laravel-collection-mapwithcast/health.svg)

```
[![Health](https://phpackages.com/badges/derheyne-laravel-collection-mapwithcast/health.svg)](https://phpackages.com/packages/derheyne-laravel-collection-mapwithcast)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.7k28.9M627](/packages/spatie-laravel-data)[spatie/laravel-livewire-wizard

Build wizards using Livewire

4061.0M4](/packages/spatie-laravel-livewire-wizard)[hirethunk/verbs

An event sourcing package that feels nice.

513162.9k6](/packages/hirethunk-verbs)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

123544.7k](/packages/worksome-exchange)[ralphjsmit/livewire-urls

Get the previous and current url in Livewire.

82270.3k4](/packages/ralphjsmit-livewire-urls)[hydrat/filament-table-layout-toggle

Filament plugin adding a toggle button to tables, allowing user to switch between Grid and Table layouts.

6292.3k1](/packages/hydrat-filament-table-layout-toggle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
