mennen-online/laravel-response-models

Convert Http JSON Responses in standard JSON Format

Downloads

2205

Stars

0

Version

2.1.0

Laravel Httpclient Response Model

This package offers a Base Model, which can be extended with Data Models to map HTTP Responses.

It is not only bound / limited to Laravels Http Client, so you can use ist with any JSON Response you want.

Installation

You can install the package via composer:

composer require mennen-online/laravel-response-models

Usage

Here's a little example how to create Response Models with this Package:

use MennenOnline\LaravelResponseModels\Models\BaseModel;

class PersonContact extends BaseModel {
    protected array $fieldMap = [
        'roles.customer.number' => 'customer_number',
        'roles.vendor.number' => 'vendor_number',
        'person' => [
            'first_name' => 'person_first_name',
            'last_name' => 'person_last_name'
        ] 
    ];   
}

Now you have defined the Response Model for PersonContact

Example Lexoffice Contact Response used for this

Now we make a Request to Lexoffice API: https://api.lexoffice.io/v1/contacts/2a730f45-8078-3ccc-a2ed-563f18208eff

We can use the Response to create the ResponseModel:

 use Illuminate\Support\Facades\Http;

$response = Http::get('https://api.lexoffice.io/v1/contacts/2a730f45-8078-3ccc-a2ed-563f18208eff');

$personContact = new PersonContact($response->object());

Now we can access the Properties on the Top Level as Properties, every other property as Array:

$personContact->version // 1

$personContact->customer_number // 12345

$personContact->__get('person.first_name') // Verena

And so on.

Also nested Arrays are automatically converted to snake_case - Accessible with Arr::get for example.

Features

Inspired of Laravel Models, it is currently possible to:

  • Define getter and setter (set{AttributeName}Attribute | get{AttributeName}Attribute)

Testing

composer test

License

The MIT License (MIT).

mennen-online

Author

mennen-online