PHPackages                             mellivora/laravel-api-caster - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. mellivora/laravel-api-caster

ActiveLibrary[Database &amp; ORM](/categories/database)

mellivora/laravel-api-caster
============================

Convert API response results to Entity objects like Laravel Eloquent. Enhanced with type-safe collections and meta support. Supports PHP 8.3+ and Laravel 10+.

v2.1.2(6mo ago)052MITPHPPHP ^8.3|^8.4CI passing

Since Jun 5Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/zhouyl/laravel-api-caster)[ Packagist](https://packagist.org/packages/mellivora/laravel-api-caster)[ Docs](https://github.com/zhouyl/laravel-api-caster)[ GitHub Sponsors](https://github.com/sponsors/zhouyl)[ RSS](/packages/mellivora-laravel-api-caster/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (13)Versions (10)Used By (0)

Laravel API Caster
==================

[](#laravel-api-caster)

[![Latest Version on Packagist](https://camo.githubusercontent.com/915b5ef625a3edd07f317fb56c08101792e65ff5bcb6f7ef6505dde92518ec04/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d656c6c69766f72612f6c61726176656c2d6170692d6361737465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mellivora/laravel-api-caster)[![GitHub Tests Action Status](https://camo.githubusercontent.com/649cac2e8b9badd8d6d702cccc84b225e6f5ff6b0641cadfc1bd15992e1c72b8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7a686f75796c2f6c61726176656c2d6170692d6361737465722f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/zhouyl/laravel-api-caster/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/3589f0c30d1249c74f7eee7677a8cc0c15124f5b798ab12ff0a720ebc2f08f62/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7a686f75796c2f6c61726176656c2d6170692d6361737465722f466978253230504850253230636f64652532307374796c652532306973737565733f6c6162656c3d636f64652532307374796c65)](https://github.com/zhouyl/laravel-api-caster/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/b619efbfa94927cf340fd1599e950847d8bea5524db849c675889e6789ab00fb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d656c6c69766f72612f6c61726176656c2d6170692d6361737465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mellivora/laravel-api-caster)

Convert API response results to Entity objects like Laravel Eloquent. This package provides a powerful and flexible way to transform API responses into structured, type-safe entities with support for casting, mapping, data transformation, and enhanced collection handling with metadata support.

Features
--------

[](#features)

- 🚀 **Laravel Eloquent-like API** - Familiar syntax for Laravel developers
- 🔄 **Automatic Type Casting** - Built-in support for common data types
- 🎯 **Custom Casters** - Create your own casting logic
- 📦 **Entity Mapping** - Map nested data to Entity objects
- 🔧 **Flexible Configuration** - Includes, excludes, renames, and more
- 📊 **Collection with Meta** - Enhanced collections with metadata support
- 🛡️ **Type-Safe Collections** - Complete type validation for all collection operations
- 🧪 **Fully Tested** - Comprehensive test suite with 84.79% coverage
- ⚡ **High Performance** - Optimized for speed and memory efficiency
- 🔒 **Type Safe** - Full PHP 8.3+ type declarations

Requirements
------------

[](#requirements)

- PHP 8.3 or 8.4
- Laravel 10.x, 11.x, or 12.x

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require mellivora/laravel-api-caster
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Mellivora\Http\Api\Entity;
use Mellivora\Http\Api\Response;

// From HTTP Response
$response = new Response($httpResponse);
$entity = Entity::from($response);

// From array data
$entity = new Entity([
    'id' => 123,
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);

// Access data
echo $entity->id;    // 123
echo $entity->name;  // John Doe
echo $entity->email; // john@example.com
```

### Collections

[](#collections)

```
// Create collection from response
$collection = Entity::collectionResponse($response);

// Create collection from array
$collection = Entity::collection([
    ['id' => 1, 'name' => 'User 1'],
    ['id' => 2, 'name' => 'User 2'],
]);

foreach ($collection as $entity) {
    echo $entity->name;
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Type Casting

[](#type-casting)

```
class UserEntity extends Entity
{
    protected array $casts = [
        'id' => 'int',
        'email_verified_at' => 'datetime',
        'settings' => 'json',
        'score' => 'decimal:2',
        'status' => UserStatusEnum::class,
    ];
}

$user = new UserEntity([
    'id' => '123',
    'email_verified_at' => '2023-01-01 12:00:00',
    'settings' => '{"theme": "dark"}',
    'score' => '95.75',
    'status' => 'active',
]);

// Automatically casted
$user->id;                 // int(123)
$user->email_verified_at;  // Carbon instance
$user->settings;           // array ['theme' => 'dark']
$user->score;              // string '95.75'
$user->status;             // UserStatusEnum::ACTIVE
```

### Entity Mapping

[](#entity-mapping)

```
class ProductEntity extends Entity
{
    protected array $mappings = [
        'category' => CategoryEntity::class,
        'tags[]' => TagEntity::class,
    ];
}

$product = new ProductEntity([
    'id' => 1,
    'name' => 'Laptop',
    'category' => ['id' => 1, 'name' => 'Electronics'],
    'tags' => [
        ['id' => 1, 'name' => 'Tech'],
        ['id' => 2, 'name' => 'Gadget'],
    ],
]);

$product->category;        // CategoryEntity instance
$product->tags;            // EntityCollection of TagEntity instances
$product->tags->first();   // TagEntity instance
```

### Field Configuration

[](#field-configuration)

```
class UserEntity extends Entity
{
    // Include only specific fields
    protected array $includes = ['id', 'name', 'email'];

    // Exclude specific fields
    protected array $excludes = ['password', 'secret'];

    // Rename fields
    protected array $renames = [
        'user_id' => 'id',
        'full_name' => 'name',
    ];

    // Append computed attributes
    protected array $appends = ['display_name'];

    public function getDisplayNameAttribute(): string
    {
        return $this->name . ' (' . $this->email . ')';
    }
}
```

### Custom Casters

[](#custom-casters)

```
use Mellivora\Http\Api\Contracts\Castable;
use Mellivora\Http\Api\Contracts\CastsAttributes;

class MoneyCaster implements Castable
{
    public static function castUsing(array $arguments): CastsAttributes
    {
        return new class implements CastsAttributes {
            public function getCastValue(Entity $entity, string $key, $value): Money
            {
                return new Money($value);
            }

            public function fromCastValue(Entity $entity, string $key, mixed $value): int
            {
                return $value->getCents();
            }
        };
    }
}

class OrderEntity extends Entity
{
    protected array $casts = [
        'total' => MoneyCaster::class,
    ];
}
```

Available Cast Types
--------------------

[](#available-cast-types)

TypeDescriptionExample`int`, `integer`Cast to integer`'123'` → `123``float`, `double`, `real`Cast to float`'12.34'` → `12.34``string`Cast to string`123` → `'123'``bool`, `boolean`Cast to boolean`1` → `true``array`Cast JSON to array`'[1,2,3]'` → `[1,2,3]``json`Alias for arraySame as array`object`Cast JSON to object`'{"a":1}'` → `stdClass``collection`Cast to Collection`[1,2,3]` → `Collection``date`Cast to Carbon date`'2023-01-01'` → `Carbon``datetime`Cast to Carbon datetime`'2023-01-01 12:00:00'` → `Carbon``timestamp`Cast timestamp to Carbon`1672574400` → `Carbon``decimal:2`Cast to decimal string`12.345` → `'12.35'``date:Y-m-d`Custom date formatCustom format`datetime:Y-m-d H:i`Custom datetime formatCustom formatTesting
-------

[](#testing)

```
composer test
```

Code Quality
------------

[](#code-quality)

```
# Run all quality checks
composer quality

# Fix code style
composer phpcs-fix

# Run static analysis
composer phpstan

# Run rector
composer rector-fix
```

API Documentation
-----------------

[](#api-documentation)

### Entity Class

[](#entity-class)

#### Methods

[](#methods)

- `__construct(iterable $attributes = [], array $meta = [])` - Create new entity
- `from(Response $response): static` - Create from Response object
- `collection(iterable $items, array $meta = []): Collection` - Create collection
- `collectionResponse(Response $response): Collection` - Create collection from Response
- `toArray(): array` - Convert to array
- `toJson(int $options = 0): string` - Convert to JSON
- `keys(): array` - Get all keys
- `values(): array` - Get all values
- `isEmpty(): bool` - Check if empty
- `copy(): static` - Create a copy
- `meta(string $key = null, mixed $default = null): mixed` - Get meta data
- `origin(string $key = null, mixed $default = null): mixed` - Get original data

### Response Class

[](#response-class)

#### Methods

[](#methods-1)

- `__construct(HttpResponse|MessageInterface $response)` - Create new response
- `code(): int` - Get response code
- `message(): string` - Get response message
- `data(string $key = null, mixed $default = null): mixed` - Get response data
- `meta(string $key = null, mixed $default = null): mixed` - Get response meta
- `toArray(): array` - Convert to array

### Caster Class

[](#caster-class)

#### Methods

[](#methods-2)

- `cast(string $cast, mixed $value): mixed` - Cast value
- `value(string $cast, mixed $value): mixed` - Get original value

Best Practices
--------------

[](#best-practices)

1. **Use Type Hints**: Always define proper types in your entity classes
2. **Leverage Caching**: Cache frequently used entities to improve performance
3. **Validate Data**: Use Laravel's validation before creating entities
4. **Handle Nulls**: Always consider null values in your casting logic
5. **Test Thoroughly**: Write tests for your custom entities and casters

Performance Tips
----------------

[](#performance-tips)

- Use `includes` to limit processed fields
- Avoid deep nesting when possible
- Cache entity instances for repeated use
- Use collections for bulk operations

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

**Issue**: "Class not found" error when using custom casters **Solution**: Ensure your caster class implements the `Castable` interface

**Issue**: Infinite recursion with circular references **Solution**: Use `excludes` to break circular references

**Issue**: Memory issues with large datasets **Solution**: Process data in chunks using collections

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance66

Regular maintenance activity

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~63 days

Recently: every ~126 days

Total

9

Last Release

202d ago

Major Versions

v1.0.4 → v2.0.02025-10-11

PHP version history (2 changes)v1.0.0PHP ^8.1

v2.0.0PHP ^8.3|^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/670a28674a5d1c4feb1817a0214b725395c08fbd0c41d5c4dc269a2f27f41620?d=identicon)[zhouyl](/maintainers/zhouyl)

---

Top Contributors

[![zhouyl](https://avatars.githubusercontent.com/u/1251541?v=4)](https://github.com/zhouyl "zhouyl (29 commits)")

---

Tags

responseapilaraveleloquententitytransformerphp8castermellivora

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mellivora-laravel-api-caster/health.svg)

```
[![Health](https://phpackages.com/badges/mellivora-laravel-api-caster/health.svg)](https://phpackages.com/packages/mellivora-laravel-api-caster)
```

###  Alternatives

[cyrildewit/eloquent-viewable

Laravel package that allows you to associate views with Eloquent models

8831.1M6](/packages/cyrildewit-eloquent-viewable)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[jerome/filterable

Streamline dynamic Eloquent query filtering with seamless API request integration and advanced caching strategies.

19226.1k](/packages/jerome-filterable)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[erlandmuchasaj/laravel-gzip

Gzip your responses.

40129.3k2](/packages/erlandmuchasaj-laravel-gzip)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
