PHP code example of eznix86 / laravel-remote-models

1. Go to this page and download the library: Download eznix86/laravel-remote-models 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/ */

    

eznix86 / laravel-remote-models example snippets


return [

    'default' => null,

    'connections' => [
        'stripe' => [
            'url' => env('STRIPE_URL', 'https://api.stripe.com'),
            'token' => env('STRIPE_SECRET'),
            'timeout' => 30,
            'retry' => ['times' => 3, 'sleep' => 100],
        ],
    ],

];

namespace App\Models\Remote\Stripe;

use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use RemoteModels\Attributes\BelongsToLocal;
use RemoteModels\Attributes\BracketFilters;
use RemoteModels\Attributes\CacheFor;
use RemoteModels\Attributes\Endpoint;
use RemoteModels\Attributes\Paging;
use RemoteModels\Attributes\Persist;
use RemoteModels\Attributes\RemoteHasMany;
use RemoteModels\Concerns\HasRemoteFactory;
use RemoteModels\RemoteModel;

#[Endpoint('/v1/customers', key: 'id', keyType: 'string')]
#[Persist('/v1/customers/{key}', method: 'post')]
#[BracketFilters]
#[Paging(perPage: 'limit', page: null)]
#[CacheFor(300)]
#[Fillable(['email', 'name', 'description', 'metadata'])]
#[RemoteHasMany(Invoice::class, as: 'invoices', foreignKey: 'customer')]
#[BelongsToLocal(User::class, remoteKey: 'metadata.user_id', ownerKey: 'id', as: 'user')]
class Customer extends RemoteModel
{
    use HasRemoteFactory;

    protected function casts(): array
    {
        return [
            'created' => 'immutable_datetime',
            'livemode' => 'boolean',
            'metadata' => 'array',
        ];
    }
}

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;

class Customer extends RemoteModel
{
    protected $connection = 'stripe';

    protected $primaryKey = 'id';

    protected $keyType = 'string';

    protected $fillable = ['email', 'name', 'description', 'metadata'];

    protected ?int $cacheFor = 300;

    protected function index(PendingRequest $http, array $query): Response
    {
        return $http->get('/v1/customers', $query);
    }

    protected function persist(PendingRequest $http, array $dirty): Response
    {
        return $http->post("/v1/customers/{$this->getKey()}", $dirty);
    }

    public function invoices(): RemoteHasMany
    {
        return $this->remoteHasMany(Invoice::class, 'customer');
    }

    public function user(): BelongsToLocal
    {
        return $this->belongsToLocal(User::class, 'metadata.user_id', 'id');
    }
}

use Illuminate\Http\Client\Response;

#[Endpoint('/api/users', key: 'id', keyType: 'int')]
#[Index('/api/users/list', method: 'post')]
#[Show('/api/users/get', method: 'post')]
#[Store('/api/users/create')]
#[Persist('/api/users/update', method: 'post')]
#[Remove('/api/users/delete', method: 'post')]
class Person extends RemoteModel
{
    protected $fillable = ['name', 'email'];

    public function resetPassword(): Response
    {
        return $this->newRemoteRequest()->post('/api/users/reset-password', [
            $this->getKeyName() => $this->getKey(),
        ]);
    }
}

$person->resetPassword();

Customer::all();
Customer::find('cus_NffrFeUfNV2Hib');
Customer::on('stripe-connect')->get();
Customer::on(['url' => 'https://api.stripe.com', 'token' => $account->stripe_secret])->get();

$customer = Customer::create(['email' => '[email protected]', 'name' => 'Taylor']);
$customer->update(['name' => 'Taylor Otwell']);
$customer->delete();

$invoices = Invoice::query()
    ->where('customer', $customer->getKey())
    ->where('status', 'open')
    ->where('created', '>=', $startOfYear)
    ->limit(100)
    ->get();

$invoices->sum('amount_due');
$invoices->groupBy('currency');
$invoices->first()->created->format('Y-m-d');

#[Scope]
protected function open(RemoteBuilder $query): RemoteBuilder
{
    return $query->where('status', 'open');
}

Invoice::open()->where('customer', 'cus_1')->get();

// GET /v1/invoices?status=open&customer=cus_1

Invoice::query()
    ->when($customer !== null, fn (RemoteBuilder $query) => $query->where('customer', $customer))
    ->when($status !== null, fn (RemoteBuilder $query) => $query->where('status', $status))
    ->get();

// GET /v1/invoices?customer=cus_1

Customer::find('cus_NffrFeUfNV2Hib');   // GET /v1/customers/cus_NffrFeUfNV2Hib
Customer::findOrFail('cus_missing');    // ModelNotFoundException on a 404
Invoice::open()->first();
Invoice::open()->exists();
Invoice::open()->count();

Invoice::open()->limit(100)->cursor()->each(function (Invoice $invoice): void {
    // ...
});

Invoice::query()
    ->where('status', 'open')
    ->where('created', '>=', $startOfYear)
    ->limit(100)
    ->get();

// GET /v1/invoices?status=open&created[gte]=1767225600&limit=100

#[Fields]                        // fields=id,email
#[Fields('fields[customer]')]    // fields[customer]=id,email

$customer->invoices;    // GET /v1/invoices?customer=cus_NffrFeUfNV2Hib
$customer->user;        // one database query on metadata.user_id

use RemoteModels\Concerns\InteractsWithRemoteModels;
use RemoteModels\Relations\HasManyRemote;

class User extends Model
{
    use InteractsWithRemoteModels;

    public function invoices(): HasManyRemote
    {
        return $this->hasManyRemote(Invoice::class, 'customer', 'stripe_id');
    }
}

$this->remoteHasMany(LineItem::class)->via('/v1/invoices/{key}/lines');
$this->remoteHasMany(Invoice::class)->via(Uri::of('/v1/invoices')->withQuery(['status' => 'open']));
$this->remoteHasMany(Invoice::class)->via(fn (Customer $customer): string => "/v1/customers/{$customer->getKey()}/invoices");

return $this->hasManyRemote(Invoice::class, 'customer', 'stripe_id')
    ->on(fn (self $user): array => [
        'url' => 'https://api.stripe.com',
        'token' => $user->team->stripe_secret,
    ]);

Customer::with('user')->get();
User::with('invoices')->get();
$customer->invoices()->where('status', 'open')->get();

Invoice::query()->limit(100)->cursor();
Invoice::query()->paginate(30);
Invoice::query()->simplePaginate(30);

use RemoteModels\NextPage;

public function nextPage(Response $response, array $query, array $records): ?NextPage
{
    if ($response->json('has_more') !== true || $records === []) {
        return null;
    }

    $last = end($records);

    return new NextPage(query: array_merge($query, [
        'starting_after' => $last['id'],
    ]));
}

use Illuminate\Support\Facades\Http;

Customer::factory()->count(3)->for($user)->create();

Http::preventStrayRequests();

$user->customers->count(); // 3

use Illuminate\Support\Facades\Http;
use RemoteModels\Facades\Remote;

Remote::extend('stripe', fn (array $config) => Http::baseUrl($config['url'])
    ->withToken($config['token'])
    ->asForm());
bash
php artisan make:remote-model Stripe/Customer --factory
http
GET /v1/invoices?customer=cus_NffrFeUfNV2Hib&status=open&created[gte]=1767225600&limit=100
bash
php artisan vendor:publish --tag="remote-models"
php artisan vendor:publish --tag="remote-models-config"
php artisan vendor:publish --tag="remote-models-stubs"