mekhtievrs/laravel-hydrator

Package for the mapping and hydrating laravel models from data arrays and collections

1.0 2023-11-22 15:36 UTC

This package is not auto-updated.

Last update: 2025-09-11 22:13:57 UTC


README

Installation

composer require mekhtievrs/hydrator

After the install package add the service provider class to config/app.php

'providers' => [
    Mekhtievrs\Hydrator\HydratorServiceProvider::class,
],

Usage

Generate data mapper

php artisan make:mapper MyCustomDataMapper

After that generator makes the mapper class, like

<?php

namespace App\Mappers;

use Mekhtievrs\Hydrator\DataMapperInterface;

class MyMapper implements DataMapperInterface
{

    public function transform(array $data) : array
    {
        return [
            // Map properties here
        ];
    }

}

Data mapping

// Map data array
$data = ['id' => 1, 'name' => 'Test 1'];

$mapped_collection = hydrator($data)->with(new MyMapper)->hydrate();
// or 
$mapped_collection = hydrator($data, new MyMapper)->hydrate();

// Map array of data array
$data = [
    ['id' => 1, 'name' => 'Test 1'],
    ['id' => 2, 'name' => 'Test 2'],
];
$mapped_collection = hydrator($data)->with(new MyMapper)->hydrate();

Data hydrate to models

// Map array of data array
$data = [
    ['id' => 1, 'name' => 'Test 1'],
    ['id' => 2, 'name' => 'Test 2'],
];
$mapped_collection = hydrator($data)->with(new MyMapper)->to(User::class)->hydrate();