PHP code example of iafilin / eloquenthttpadapter

1. Go to this page and download the library: Download iafilin/eloquenthttpadapter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

iafilin / eloquenthttpadapter example snippets


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');
    }
}

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 `wheres` from the query object
            foreach ($this->getQuery()->wheres as $where) {
                $params["filter[{$where['column']}"] = $where['value'];
            }

            return $params;
        });
    }
}

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

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

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

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

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

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;
        });
    }
}