PHP code example of derheyne / laravel-collection-mapwithcast

1. Go to this page and download the library: Download derheyne/laravel-collection-mapwithcast library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

derheyne / laravel-collection-mapwithcast example snippets


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

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

// 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);
    }
}

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']

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

// Result: [12.6, 24.9, 36.0]

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

// Result: [6, 15]

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

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

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']
shell
php artisan vendor:publish --tag=laravel-collection-mapwithcast-config