PHPackages                             m-tech-stack/laravel-api-model-client - 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. m-tech-stack/laravel-api-model-client

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

m-tech-stack/laravel-api-model-client
=====================================

A powerful Laravel package that enables Eloquent-like models to interact seamlessly with external APIs instead of a local database

1.2.19(4mo ago)1321MITPHPPHP ^8.0|^8.1|^8.2|^8.3

Since Aug 24Pushed 2mo agoCompare

[ Source](https://github.com/mabou7agar/laravel-api-model-client)[ Packagist](https://packagist.org/packages/m-tech-stack/laravel-api-model-client)[ RSS](/packages/m-tech-stack-laravel-api-model-client/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (8)Versions (39)Used By (0)

🚀 Laravel API Model Client with OpenAPI Integration
===================================================

[](#-laravel-api-model-client-with-openapi-integration)

[![Latest Version on Packagist](https://camo.githubusercontent.com/929c3d0b93173f09e5bdbb4921d30d9ba4ea0c778f1e07397731e091d4ca9561/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d2d746563682d737461636b2f6c61726176656c2d6170692d6d6f64656c2d636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m-tech-stack/laravel-api-model-client)[![Total Downloads](https://camo.githubusercontent.com/f5c6e77906124715c02c5f554046987178ab07c60421a8bbf7e183aa1a80dce4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d2d746563682d737461636b2f6c61726176656c2d6170692d6d6f64656c2d636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m-tech-stack/laravel-api-model-client)[![License](https://camo.githubusercontent.com/f83f60513ee4fabd63dcbf389199e893af2af22976026d476b155ad2766139e3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d2d746563682d737461636b2f6c61726176656c2d6170692d6d6f64656c2d636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/m-tech-stack/laravel-api-model-client)[![Laravel Version](https://camo.githubusercontent.com/11ba5d99015522487fdaeafecd4de3c8f5e91bafd16811422ad0af48afd92dde/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302e7825323025374325323031312e7825323025374325323031322e782d6f72616e67652e7376673f7374796c653d666c61742d737175617265)](https://laravel.com)[![OpenAPI](https://camo.githubusercontent.com/1cd83c588dc21f0fb7a899c50b55826dd7338971e64d36fe9ddd9ce8f3119dea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4f70656e4150492d332e302532422d626c75652e7376673f7374796c653d666c61742d737175617265)](https://swagger.io/specification/)[![PHP Version](https://camo.githubusercontent.com/b1d4b2140def998a738394dc2a0a77846d311964dca956b1f7ba869093f47ee5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d707572706c652e7376673f7374796c653d666c61742d737175617265)](https://php.net)[![Tests](https://camo.githubusercontent.com/0b56daed4bfcaf431db1391c8aedc3f0ea8f17ee672544514f1ede383b4d93ab/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54657374732d393825323525323050617373696e672d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](#-testing)[![Quality Score](https://camo.githubusercontent.com/a954b7e5ebf7676d7ff80d15c51f09911e7ca7a54d7f19bc358005230b8f38c3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5175616c6974792d412b2d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](#-features)[![Attribute Flattening](https://camo.githubusercontent.com/53896c92eac24aa35992d84ea1c1a2c49ac3d64b0ab0e1064b912c846c7d186e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f417474726962757465253230466c617474656e696e672d46697865642d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](#-recent-fixes)[![Trait Cleanup](https://camo.githubusercontent.com/7b164cf799e32248b36b70a6c9546b8c79b38e7557f0278afe4f52435744fa77/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54726169742532304172636869746563747572652d436c65616e2d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](#-recent-fixes)

**Transform your Laravel applications with Eloquent-like API models powered by OpenAPI specifications**

*Build robust, type-safe API integrations with automatic model generation, intelligent caching, and comprehensive relationship support*

---

🌟 Why Choose Laravel API Model Client?
--------------------------------------

[](#-why-choose-laravel-api-model-client)

**The most advanced Laravel package for API integration** - Transform external APIs into familiar Eloquent models with zero configuration complexity.

✨ **OpenAPI-First Approach** - Automatic model generation from your API specifications
🔄 **Eloquent Compatibility** - Use familiar Laravel syntax with external APIs
⚡ **High Performance** - Intelligent caching and query optimization
🛡️ **Type Safety** - Full schema validation and type checking
🔗 **Relationship Support** - Complete relationship mapping and lazy loading

> 🎉 **NEW in v1.2.1**: Complete attribute flattening fixes, clean trait architecture, and comprehensive API response handling!
>
> 🔧 **MAJOR FIXES**: All attribute flattening issues resolved - no more single 'data' attribute pollution!

📋 Table of Contents
-------------------

[](#-table-of-contents)

Click to expand navigation- [🌟 Why Choose Laravel API Model Client?](#-why-choose-laravel-api-model-client)
- [🔧 Recent Major Fixes](#-recent-major-fixes)
- [🚀 Features](#-features)
- [📦 Installation](#-installation)
- [⚡ Quick Start](#-quick-start)
- [📖 OpenAPI Integration](#-openapi-integration)
    - [Automatic Model Generation](#automatic-model-generation)
    - [Schema Validation](#schema-validation)
    - [Dynamic Query Building](#dynamic-query-building)
    - [Multi-Schema Support](#multi-schema-support)
- [🏗️ Basic Usage](#%EF%B8%8F-basic-usage)
- [🔗 API Relationships](#-api-relationships)
- [🔍 Query Builder](#-query-builder)
- [⚡ Caching](#-caching)
- [🔐 Authentication](#-authentication)
- [🛠️ Artisan Commands](#%EF%B8%8F-artisan-commands)
- [🧪 Testing](#-testing)
- [📊 Performance &amp; Benchmarks](#-performance--benchmarks)
- [🔧 Configuration](#-configuration)
- [📚 Documentation](#-documentation)
- [🚨 Troubleshooting](#-troubleshooting)
- [🗺️ Roadmap](#%EF%B8%8F-roadmap)
- [🤝 Contributing](#-contributing)
- [📄 License](#-license)

🔧 Recent Major Fixes
--------------------

[](#-recent-major-fixes)

### ✅ **Comprehensive Attribute Flattening Resolution (v1.2.1)**

[](#-comprehensive-attribute-flattening-resolution-v121)

**Problem Solved**: API responses were being stored in a single `data` attribute instead of being flattened into individual model attributes.

**Root Cause Found**: Multiple methods were using `mapApiAttributes()` and `fill()` instead of the proper `newFromApiResponse()` method.

**Fixed Methods**:

- ✅ `find()` method in `ApiModelQueries.php`
- ✅ `all()` method in `ApiModelQueries.php`
- ✅ `save()` method in `ApiModelQueries.php`
- ✅ `createViaApi()` method in `ApiModel.php`
- ✅ `updateViaApi()` method in `ApiModel.php`

**Before (Problematic)**:

```
$product = Product::find(1);
echo $product->data['name']; // ❌ All data in single attribute
```

**After (Fixed)**:

```
$product = Product::find(1);
echo $product->name;  // ✅ Individual attributes accessible
echo $product->id;    // ✅ Clean attribute access
echo $product->sku;   // ✅ No data pollution
```

### 🧹 **Complete Trait Architecture Cleanup**

[](#-complete-trait-architecture-cleanup)

**Removed Problematic Methods**:

- ❌ Infinite recursion in `HasApiOperations::newFromApiResponse()`
- ❌ Complex reflection logic in `LazyLoadsApiRelationships`
- ❌ Method conflicts between traits

**Result**: Clean, professional trait architecture with no conflicts or redundant code.

### 🔧 **Enhanced Metadata Storage**

[](#-enhanced-metadata-storage)

- ✅ Separate `$apiResponseData` property for metadata
- ✅ Clean model serialization without pollution
- ✅ Original API response accessible via `getApiResponseData()`

---

🚀 Features
----------

[](#-features)

### 🎯 **OpenAPI Integration (NEW)**

[](#-openapi-integration-new)

- **🔄 Automatic Model Generation**: Generate Laravel models directly from OpenAPI 3.0+ specifications
- **✅ Schema Validation**: Validate API requests/responses against OpenAPI schemas with configurable strictness
- **🔍 Dynamic Query Building**: Build queries with automatic OpenAPI parameter validation and transformation
- **🔗 Relationship Detection**: Automatic relationship mapping from OpenAPI `$ref` references
- **📊 Multi-Schema Support**: Handle multiple API versions and schemas simultaneously
- **⚡ Performance Optimization**: Schema caching, lazy loading, and intelligent query optimization

### 🏗️ **Core Capabilities**

[](#️-core-capabilities)

- **Eloquent-like API Models**: Work with external APIs using familiar Eloquent syntax with full Laravel integration
- **Hybrid Data Source Management**: Intelligent switching between database and API with 5 sophisticated modes
- **Advanced Multi-Layer Caching**: High-performance caching system with Redis support and configurable TTL
- **Comprehensive Query Builder**: Chainable query methods with advanced filtering, sorting, and pagination
- **Full API Relationships**: Complete relationship support with lazy loading and eager loading optimization

### 🔧 **Advanced Features**

[](#-advanced-features)

- **Multi-Authentication Support**: Bearer tokens, Basic auth, API keys, OAuth2, and custom authentication strategies
- **Robust Error Handling**: Circuit breaker pattern, retry logic, fallback mechanisms, and detailed logging
- **Event-Driven Architecture**: Laravel event integration with custom API model events and lifecycle hooks
- **Extensible Middleware Pipeline**: Built-in middleware for authentication, rate limiting, caching, and validation
- **Powerful Response Transformers**: Transform API responses with custom transformer classes and data mapping
- **Intelligent Database Synchronization**: Seamless sync between API and local database with conflict resolution

### 🎯 **Enterprise Features**

[](#-enterprise-features)

- **High-Performance Caching**: Redis-based caching with intelligent cache warming and distributed support
- **Testing Framework**: Comprehensive testing utilities, mock factories, and API response mocking
- **Console Commands**: Rich set of Artisan commands for schema validation, model generation, and debugging
- **Developer Tools**: OpenAPI schema parsing, model generation, and comprehensive documentation
- **Migration Tools**: Seamless migration from manual to OpenAPI-driven configuration
- **Monitoring &amp; Debugging**: Performance monitoring, health checks, and detailed error reporting

📦 Installation
--------------

[](#-installation)

### Requirements

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.0 or higher
- OpenAPI 3.0+ specification (for OpenAPI features)

### Install via Composer

[](#install-via-composer)

```
# Install the main package
composer require m-tech-stack/laravel-api-model-client

# Install OpenAPI dependency for schema parsing
composer require cebe/php-openapi
```

### Publish Configuration

[](#publish-configuration)

```
# Publish all configuration files
php artisan vendor:publish --provider="MTechStack\LaravelApiModelClient\ServiceProvider"

# Or publish specific configurations
php artisan vendor:publish --tag="api-client-config"
php artisan vendor:publish --tag="api-client-examples"
```

### Environment Setup

[](#environment-setup)

```
# Copy example environment variables
cp .env.api-client.example .env.local

# Add to your .env file
API_CLIENT_PRIMARY_SCHEMA=https://api.example.com/openapi.json
API_CLIENT_PRIMARY_BASE_URL=https://api.example.com
API_CLIENT_PRIMARY_TOKEN=your-api-token
```

⚡ Quick Start
-------------

[](#-quick-start)

### 1. Basic Configuration

[](#1-basic-configuration)

```
// config/api-client.php
return [
    'schemas' => [
        'primary' => [
            'source' => env('API_CLIENT_PRIMARY_SCHEMA'),
            'base_url' => env('API_CLIENT_PRIMARY_BASE_URL'),
            'authentication' => [
                'type' => 'bearer',
                'token' => env('API_CLIENT_PRIMARY_TOKEN'),
            ],
            'validation' => [
                'enabled' => true,
                'strictness' => 'moderate', // strict, moderate, lenient
            ],
            'caching' => [
                'enabled' => true,
                'ttl' => 3600,
            ],
        ],
    ],
];
```

### 2. Create Your First Model

[](#2-create-your-first-model)

```
