Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Data Helpers Laravel Package

event4u/data-helpers

event4u/data-helpers offers practical PHP and Laravel utilities for working with structured data, including helpers for arrays, DTOs, validation, and transformations, helping reduce boilerplate and keep application code cleaner, safer, and more consistent.

View on GitHub
Deep Wiki
Context7

Getting Started

Install

composer require event4u/data-helpers

The package ships with zero required dependencies — Laravel, Symfony, and Doctrine integrations are optional add-ons pulled in only if the corresponding framework is detected. On Laravel 9–11 the service provider should be auto-discovered; if you're on a skeletal install or a non-standard app, check config/app.php providers after composer dump-autoload.

Where to look first

Source Why
starlight/src/content/docs/ (built via task docs:dev) Canonical docs; every example is executable
tests/Documentation/ The same examples as Pest tests — the most trustworthy API reference
examples/ Runnable end-to-end snippets
src/SimpleDto.php, src/LiteDto.php The two DTO base classes you'll actually extend
src/Frameworks/ Laravel service provider, Route Model Binding, request integration

Because the doc examples are covered by the Documentation test suite, anything you copy out of the docs is verified against CI — treat docs over blog posts.

First use case (the 5-minute win)

Swap a nest of data_get() / Arr::get() calls for DataAccessor:

use event4u\DataHelpers\DataAccessor;

$accessor = new DataAccessor($payload); // array, object, or model

$accessor->get('user.address.city');            // dot notation
$accessor->has('user.address.city');

Then, the moment you're passing the same array around three layers deep, promote it to a SimpleDto — that's the point where the package starts paying rent.


Implementation Patterns

1. Request → DTO at the controller boundary

The highest-value pattern in a Laravel app: stop passing Request objects into services.

use event4u\DataHelpers\SimpleDto;

final readonly class CreateOrderDto extends SimpleDto
{
    public function __construct(
        public int $customerId,
        public array $items,
        public ?string $coupon = null,
    ) {}
}
public function store(CreateOrderRequest $request): OrderResource
{
    $dto = CreateOrderDto::from($request->validated());

    return new OrderResource($this->orders->create($dto));
}

Rules of thumb:

  • SimpleDto → immutable, full-featured, validation built in. Default choice.
  • LiteDto → minimalistic / fastest. Use for hot paths (bulk import, per-row mapping in queues) where you've measured and the DTO hydration cost shows up. Don't reach for it first.

2. Validation lives on the DTO, not the FormRequest

The package has its own Validation/ engine. For input coming from HTTP you can keep Laravel's FormRequest (familiar, authorize(), error bag integration) and use the DTO purely as a typed carrier. For non-HTTP entry points — queue payloads, CSV imports, webhook bodies, third-party SDK responses — use the package's validation so the rule lives next to the shape it validates.

Pick one boundary per layer and be consistent. Mixing both on the same class leads to double validation and two error formats.

3. DataMapper for third-party payloads

This is the killer feature for anyone integrating APIs with hostile field names:

$order = DataMapper::map($vendorPayload, [
    'id'         => 'order.reference',
    'total'      => 'order.amounts.gross.value',
    'placed_at'  => 'order.meta.created',
    'customer.id'=> 'buyer.uid',
]);

Keep the mapping template in a config file or a dedicated Mappings/ directory rather than inline — vendor APIs change field names silently, and a one-line template diff is a far better review than a 40-line controller diff.

4. DataFilter as SQL-for-arrays

For in-memory collections, reporting endpoints, or cached datasets where you'd otherwise pull rows into PHP and array_filter by hand:

$results = DataFilter::filter($rows, [
    'status'    => 'paid',
    'total >'   => 100,
]);

Use it when the dataset is already in memory. Do not use it as a substitute for the query builder — if the data lives in MySQL, let MySQL filter it. The moment you find yourself loading ->all() to filter in PHP, you've made a mistake.

5. Converters/ at the edges of the system

Converters/ handles JSON, XML, YAML, and CSV. Practical placements:

  • Import jobs: CSV → array → DataMapper → DTO → Eloquent. The CSV converter plus the mapping layer collapses a whole class of "parse and normalise" services.
  • Export commands: DTO collection → CSV for a scheduled nightly dump to S3.
  • XML integrations: SOAP/legacy feed ingestion where simpleXmlToArray() gives you something DataAccessor can walk with dot notation.

6. Route Model Binding

The package adds Route Model Binding support. If you're using it, register the binding explicitly in a service provider rather than relying on implicit behaviour — with 14 stars and 0 dependents, treat "it just works" as something to verify in a feature test, not to assume.

7. Collections as return types

DataCollection is the type-safe counterpart to a raw array. Returning DataCollection from a service method gives the caller filter/map/dot-access for free and keeps type information that array throws away. Good fit for repository-ish layers and for anything that crosses an HTTP boundary into a JSON resource.

8. Cache warming on deploy

There's a Console/ directory with cache warming commands and a CacheDriver enum. If you enable caching in production, add the warm command to your deploy pipeline, right after config:cache. A cold cache on a fresh container is the classic way this package bites people.


Gotchas and Tips

Dot notation is ambiguous with dotted keys. A key literally named user.name in your source array will collide with a nested path user → name. If you ingest data with dots in keys (common in Elasticsearch hits, Prometheus, some SaaS webhooks), normalise or escape them before handing to DataAccessor/DataMutator.

PHP ^8.2 is a hard floor. If any service in your fleet is still on 8.1, this package is a non-starter there. Check composer.json platform config before you plan the rollout.

Laravel 12 is not in the test matrix. Officially validated against Laravel 9–11. It may work on 12, but you're the test suite at that point — pin your laravel/framework constraint and add a smoke test covering the service provider boot, DTO hydration, and route binding if you're on 12.

Zero dependencies ≠ zero footprint. The integrations are optional, which means they're conditional. If autodiscovery doesn't register what you expect (config not published, Route Model Binding missing), don't debug the package — first confirm the Laravel integration actually loaded.

Validation rules are not Laravel rules. The Validation/ engine is its own implementation. 'email', 'required', and 'max:255' may mean something subtly different, and rules you take for granted (exists:users,id, unique, current_password) likely aren't there. Read the validation docs before porting a FormRequest wholesale, and keep DB-touching rules in Laravel where the query builder is.

Cache invalidation is on you. Mapping templates and DTO metadata get cached. If a mapping "doesn't take effect" after a deploy, you forgot the warm command or a cache clear. First debugging step for any "my change did nothing" report.

SimpleDto vs LiteDto is a one-way door in practice. Start with SimpleDto. LiteDto deliberately drops features; swapping back later means touching every call site. Choose LiteDto only after a benchmark says so — the repo has a benchmarks/ suite with PHPBench, so run it against your actual payload shape rather than trusting a README number.

Don't touch src/Support/. Internals, deliberately excluded from ECS and Rector. If you're vendoring or patching, expect nothing there to be stable across releases.

Debugging tips

  • Dump the intermediate shape, not the final DTO: run the raw array through DataAccessor and check each dot path individually. Most "mapping is broken" issues are a single wrong path segment.
  • The Documentation test suite is your oracle. If behaviour contradicts the docs, you've found a bug — check the release date against your lockfile before working around it.
  • var_dump()/dd()/die() are disallowed in the package's own standards; that signals the maintainers expect structured debugging (the Logging/ directory). Use Log::debug() on the accessor output rather than littering the codebase.

Extension points worth knowing

  • Enums (CacheDriver, Mode) — prefer configuring via enum case over strings; typo'd strings fail silently in config files.
  • Custom converters — if you need Parquet/NDJSON/Excel, the Converters/ structure is the intended seam rather than a bespoke parser in your app.
  • Helpers/ (DotPath, Object, Env, Config, Math) — DotPathHelper in particular is worth importing directly if you need just path resolution without the full accessor.

Overall verdict for a Laravel team: the DTO + mapping layer is genuinely useful and the SQL-like filtering is a nice differentiator for in-memory/cached datasets. The risk isn't code quality (PHPStan Level 9, Pest, ECS, three PHP versions in CI is a serious setup) — it's the 14 stars / 0 dependents signal. Budget for reading src/ on anything you rely on, keep the package behind your own thin adapter/wrapper classes so you can swap it, and pin the version.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource