hamidmp / dualresource
DualResource - Parameters mapper for both request and response
v1.0.1
2021-12-30 11:38 UTC
Requires
- php: ^7.4|^8.0
This package is not auto-updated.
Last update: 2024-11-15 02:08:26 UTC
README
DualResource is a derived class of Laravel Resource.
By DualResource, in addition what API Resource can to do, you can map request data to array with same template.
- Map Request Data To new array
- Map Model To json
Installation
Require with Composer
composer require hamidmp/dualresource
Usage
class Person { // firstName, lastName, city, ... public function cars(){ return $this->hasMany(Car::class); } } class Car { // person_id, name, model, ... }
1. Using fname
and lname
instead of firstName
and lastName
in client side (API or UI)
class PersonDualResource extends DualResource { protected function mapFields() { return [ 'fname'=>'fisrtName', 'lname'=>'lastName', ]; } }
$data = PersonDualResource::fromRequest($request)->getParameters(); //$request contained: fname, lname //$data will contain: firstName , lastName
Note: Method mapFields
will generate toArray
method and you don't need to change it.
2. With relationship
class PersonDualResource extends DualResource { protected function mapFields() { return [ 'fname'=>'fisrtName', 'lname'=>'lastName', 'car_list'=>['cars',CarDualResource::class], ]; } }
$data = PersonDualResource::fromRequest($request)->getParameters(); //$request contained: fname, lname, car_list:[ {name, model},... ] //$data will contain: firstName , lastName, cars=>[ [name,model],... ]
3. Using anonymous function for mapping
class PersonDualResource extends DualResource { protected function mapFields() { return [ 'fname'=>'fisrtName', 'lname'=>'lastName', 'car_list'=>['cars',function($key){ //for response return CarDualResource::collection($this->{$key}); },function($data){ //for request return CarDualResource::fromRequestData($data); }], ]; } }
Note: You can ignore each function by returning null
value: return null;
4. Using as normal Resource class (for response)
$person=\App\Models\Person::with('cars')->find(1); return \App\Http\Resources\PersonDualResource::fromModel($person)->response();
Methods
- Preparing class
//Declaring assign-map between model and data //return array protected function mapFields()
- from request data
//Preparing DualResource for mapping data from request public static function fromRequest(Request $request) //return array of mapped request data public function getParameters($extra=[], $defaults=[]) //return array of mapped request data plus other ones public function getAll($extra=[], $defaults=[])
- for response (json)
//return a new resource instance from one model public static function fromModel(...$parameters) //return a new anonymous resource collection from Models public static function fromModels($resource)
License
The DualSource library is open-sourced software licensed under the MIT license.