Usage

Data transfer objects are useful to pass data, they can be used everywhere but has some special uses in multiple places like controllers (including their route bindings) and queued jobs.

In case of using the mapper there is a namespaced function to be used to simplify its usage:

use Carbon\Carbon;

use function OpenSoutheners\LaravelDataMapper\map;

$mappedValue = map(1747939147)->to(Carbon::class);

Mappers

These capabilities are called internally as mappers and they can be used to extend the functionalities of this mapper in 2 different ways.

These are the currently built-in mappers:

  • Collections: Map delimited lists strings or arrays of data into Laravel collections.

  • Objects: Map JSON strings or arrays of data into class objects.

  • Generic objects: Map JSON strings or arrays of data into \stdClass objects.

  • Carbon: Map UNIX numeric timestamps or timestamps in different formats to a Carbon instance.

  • Backed enums: Map string or integer to a backed enum case.

  • Models: Map delimited lists strings or string/numeric keys to an Eloquent model instance.

Collections

use Illuminate\Support\Collection;

map(['Ruben', 'Taylor'])->to(Collection::class);
map('Ruben, Taylor')->to(Collection::class);
map('Ruben', 'Taylor')->to(Collection::class);

Objects

This topic is extended in the following page.

class UserObject
{
    public function __construct(public string $name, public string $surname) {}
}

map(['name' => 'Taylor', 'surname' => 'Otwell'])->to(UserObject::class);
map('{"name": "Taylor", "surname": "Otwell"}')->to(UserObject::class);

Generic objects

map(['name' => 'Taylor', 'surname' => 'Otwell'])->to(\stdClass::class);

Carbon

use Illuminate\Support\Carbon;

map(1747939147)->to(Carbon::class);
map('1747939147')->to(Carbon::class);
map('2025-05-22')->to(Carbon::class);

Backed enums

enum UserStatus: int
{
    case Active = 1;
    
    case Inactive = 2;
    
    case Banned = 3;
}

map(1)->to(UserStatus::class);
map('2')->to(UserStatus::class);

Models

use App\Models\User;

map(1)->to(User::class);
map(1, 2)->to(User::class);

Mapping through

In some contexts we probably want a collection of mapped data results from the mapper, in this cases there is the through method, in the following it will return a Collection of Carbon instances:

use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

map(1747939147, 1781934121)->through(Collection::class)->to(Carbon::class);

Last updated

Was this helpful?