PHPackages                             iafilin/eloquenthttpadapter - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. iafilin/eloquenthttpadapter

ActiveLibrary[HTTP &amp; Networking](/categories/http)

iafilin/eloquenthttpadapter
===========================

EloquentHttpAdapter is a Laravel package that allows you to work with RESTful API data using an Eloquent-like syntax with HttpModel abstract class, interfaces, and custom exceptions.

v2.0.0(9mo ago)81281[1 PRs](https://github.com/iafilin/eloquenthttpadapter/pulls)MITPHPPHP ^8.0

Since Nov 14Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/iafilin/eloquenthttpadapter)[ Packagist](https://packagist.org/packages/iafilin/eloquenthttpadapter)[ Docs](https://github.com/iafilin/eloquenthttpadapter)[ RSS](/packages/iafilin-eloquenthttpadapter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (7)Versions (9)Used By (0)

Donate:
------------------------------------------

[](#donate-httpsboostytoiafilindonate)

EloquentHttpAdapter
===================

[](#eloquenthttpadapter)

**EloquentHttpAdapter** is a Laravel package that provides an alternative to [calebporzio/sushi](https://github.com/calebporzio/sushi). It allows you to work with RESTful API data using an Eloquent-like syntax.

This package was originally developed to integrate [Filament](https://filamentphp.com) with APIs, making it a convenient tool for admin panels. However, thanks to its flexibility, it can also be used for any task requiring API integration with an Eloquent-like interface.

---

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

[](#installation)

Install the package via Composer:

```
composer require iafilin/eloquenthttpadapter
```

---

Usage
-----

[](#usage)

### Setting Up a Model

[](#setting-up-a-model)

To enable API integration, use the `InteractsWithHttp` trait and define a custom `httpClient` method to configure the HTTP client:

```
namespace App\Models;

use Iafilin\EloquentHttpAdapter\InteractsWithHttp;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Client\PendingRequest;

class Purchase extends Model
{
    use InteractsWithHttp;

    /**
     * Configure the HTTP client with the API endpoint.
     */
    private static function httpClient(): PendingRequest
    {
        return \Http::baseUrl('/api/admin/purchases');
    }
}
```

---

### Registering a Fetch Parameters Resolver

[](#registering-a-fetch-parameters-resolver)

You can define the logic for building HTTP query parameters using the `registerFetchParamsResolver` method. This allows dynamic configuration of pagination, filtering, and sorting parameters.

Additionally, within the resolver, you have access to the `getQuery()` object, which lets you retrieve Eloquent `wheres` conditions and use them to generate HTTP parameters.

Example setup:

```
class Purchase extends Model
{
    use InteractsWithHttp;

    protected static function boot()
    {
        parent::boot();

        static::registerFetchParamsResolver(function ($page, $perPage) {
            $params = [
                'page' => $page,
                'per_page' => $perPage),
            ];

            // Parse `wheres` from the query object
            foreach ($this->getQuery()->wheres as $where) {
                $params["filter[{$where['column']}"] = $where['value'];
            }

            return $params;
        });
    }
}
```

---

API Requirements
----------------

[](#api-requirements)

To ensure compatibility with the package, your API should follow these conventions:

1. **Standard REST endpoints:**

    - `POST /api/resource` — Create records.
    - `GET /api/resource` — Fetch records (paginated or full list).
    - `GET /api/resource/{id}` — Fetch a single record.
    - `PUT /api/resource/{id}` — Update a record.
    - `DELETE /api/resource/{id}` — Delete a record.
2. **Response Structure:**

    - **Lists:** Should include `data`, `total`, `per_page`, and `current_page`.
    - **Single Record:** Should return attributes directly without nesting.

Example paginated response:

```
{
    "data": [
        { "id": 1, "name": "Item 1" },
        { "id": 2, "name": "Item 2" }
    ],
    "total": 50,
    "per_page": 10,
    "current_page": 1
}
```

3. **Pagination:**

    - Support for `page` and `per_page` query parameters.
4. **Filters and Sorting:**

    - Filters: `filter[column]=value`.
    - Sorting: `sort=column` for ascending and `sort=-column` for descending.

---

CRUD Operations
---------------

[](#crud-operations)

Once your model is set up, you can use standard Eloquent methods to interact with your API:

### Create a Record

[](#create-a-record)

```
$purchase = Purchase::create(['name' => 'New Item']);
```

### Read Records

[](#read-records)

```
$purchases = Purchase::all(); // Fetch all records
$purchases = Purchase::paginate(10); // Paginate results
```

### Update a Record

[](#update-a-record)

```
$purchase = Purchase::find(1);
$purchase->update(['name' => 'Updated Name']);
```

### Delete a Record

[](#delete-a-record)

```
$purchase = Purchase::find(1);
$purchase->delete();
```

---

Customizing HTTP Requests
-------------------------

[](#customizing-http-requests)

You can fully customize HTTP request behavior by overriding the `httpClient` method in your model. For example, adding headers or specific configurations:

```
private static function httpClient(): PendingRequest
{
    return \Http::baseUrl('/api/admin/purchases')
                ->withHeaders(['Authorization' => 'Bearer token']);
}
```

---

If you have any questions or suggestions, feel free to open an issue or contribute! 💡

---

### Customizing API Fetch Parameters with `registerFetchParamsResolver`

[](#customizing-api-fetch-parameters-with-registerfetchparamsresolver)

The `registerFetchParamsResolver` method allows you to customize the HTTP query parameters sent to your API for fetching data. It provides a powerful way to dynamically build parameters like pagination, filters, and sorting based on the current Eloquent query or incoming user requests.

With access to the Eloquent query object (`$this->getQuery()`), you can parse `wheres`, `orders`, and other query conditions, transforming them into HTTP parameters compatible with your API.

#### Key Benefits:

[](#key-benefits)

- **Dynamic configuration:** Automatically adapt HTTP query parameters to match user input or specific query requirements.
- **Seamless integration:** Utilize existing Eloquent query methods while maintaining API compatibility.
- **Support for complex queries:** Build filters, pagination, and sorting logic based on both application and API needs.

#### Example Usage:

[](#example-usage)

```
class Purchase extends Model
{
    use InteractsWithHttp;

    protected static function boot()
    {
        parent::boot();

        static::registerFetchParamsResolver(function () {
            $params = [
                'page' => request()->query('page', 1),
                'per_page' => request()->query('per_page', 10),
            ];

            // Parse where conditions from the query object
            foreach ($this->getQuery()->wheres as $where) {
                $params["filter[{$where['column']}"]"] = $where['value'];
            }

            return $params;
        });
    }
}
```

This makes it easy to dynamically adapt HTTP query parameters based on user input or predefined conditions in your Laravel application.

Error Handling
--------------

[](#error-handling)

The package automatically logs errors during API interactions and returns `null` in case of failure. This ensures graceful handling of API downtime or errors without throwing exceptions.

---

License
-------

[](#license)

This package is open-source and licensed under the [MIT license](license.md).

###  Health Score

36

—

LowBetter than 81% of packages

Maintenance63

Regular maintenance activity

Popularity16

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 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 ~53 days

Recently: every ~65 days

Total

6

Last Release

274d ago

Major Versions

1.0.4 → v2.0.02025-08-08

### Community

Maintainers

![](https://www.gravatar.com/avatar/97f4c30dedeadbd7fc7e76d9ea98563d9885d059da74a1461f4ba17cd471c670?d=identicon)[iafilin](/maintainers/iafilin)

---

Top Contributors

[![iafilin](https://avatars.githubusercontent.com/u/26049079?v=4)](https://github.com/iafilin "iafilin (2 commits)")

---

Tags

httpapiinterfaceslaravelresteloquentexceptionsadapterEloquentHttpAdapterHttpModel

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/iafilin-eloquenthttpadapter/health.svg)

```
[![Health](https://phpackages.com/badges/iafilin-eloquenthttpadapter/health.svg)](https://phpackages.com/packages/iafilin-eloquenthttpadapter)
```

###  Alternatives

[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)[bjerke/api-query-builder

A query builder for Laravel that parses the request and uses Eloquent ORM to query database

267.7k1](/packages/bjerke-api-query-builder)[dragon-code/laravel-http-logger

Logging incoming HTTP requests

319.8k3](/packages/dragon-code-laravel-http-logger)[bjerke/laravel-bread

A boilerplate package for BREAD operations through REST API in Laravel

115.2k](/packages/bjerke-laravel-bread)[laragear/api-manager

Manage multiple REST servers to make requests in few lines and fluently.

161.8k](/packages/laragear-api-manager)[rap2hpoutre/jacky

Opinionated REST JSON HTTP API client for laravel

174.4k](/packages/rap2hpoutre-jacky)

PHPackages © 2026

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