PHP code example of hamidmp / dualresource

1. Go to this page and download the library: Download hamidmp/dualresource 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/ */

    

hamidmp / dualresource example snippets


class Person {
    // firstName, lastName, city, ...
    
    public function cars(){
        return $this->hasMany(Car::class);
    }
}

class Car {
    // person_id, name, model, ...   
}

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 

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],... ] 

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

            }],
        ];
    }

}

$person=\App\Models\Person::with('cars')->find(1);
return \App\Http\Resources\PersonDualResource::fromModel($person)->response();

//Declaring assign-map between model and data
//return array 
protected function mapFields()

//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=[])

//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)