digitalhq / hydrator
Package for the mapping and hydrating laravel models from data arrays and collections
dev-master
2021-08-23 00:10 UTC
Requires
- php: ^7.4|^8.0
- illuminate/console: ^7.0|^8.0
- illuminate/support: ^7.0|^8.0
Requires (Dev)
- ext-json: *
This package is not auto-updated.
Last update: 2025-06-23 15:58:18 UTC
README
Installation
composer require digitalhq/hydrator
After the install package add the service provider class to config/app.php
'providers' => [
Digitalhq\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 Digitalhq\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();