nick2price
3 years ago

Convert data back into a Model

Posted 3 years ago by nick2price

Hi I have 2 systems, both are similar but they are seperate systems. Both systems have their own Project model, along with its relationships, the models are the same within both systems.

I need to send a Project with its relationships from System A to System B. To do this I do the following

$client = new GuzzleHttp\Client();
$jsonProject = json_encode(Project::with('projectType', 'projectType.projectTypeData',
                            'projectAssets', 'projectAssets.projectAssetsData')->find($project->id));

$req = $client->request('POST', 'https://someurl/postProject', [
    'body' => json_encode($jsonProject),
    'headers' => [
        'Content-Type' => 'application/json',
        'Content-Length' => strlen($jsonProject),
    ]
]);

Now withing System B the above triggers the following function

public function store(Request $request)
{
     $projectData = json_decode($request->getContent(), true);
     dd($campaignData);
}

This essentially outputs something like the following

array:17 [
  "id" => 3
  "projectName" => "Test Project"
  "user_id" => 1
  "contact" => "John Doe"
  "project_type" => array:7 [
    "id" => 3
    "project_id" => 3
    "project_type_data" => array:1 [
      0 => array:8 [
        "id" => 5
        "projectType" => "Standard"
      ]
    ]
  ]
  "project_assets" => array:7 [
    "id" => 2
    "project_id" => 3
    "project_assets_data" => array:4 [
      0 => array:8 [
        "id" => 5
        "label" => "Logo"
        "altTag" => ""
        "urlPath" => ""
        "projectAssetsId" => 2
      ]
    ]
  ]
]

Within System B I now need to convert this back into a Project Object, along with its relationships. I see that I could do something like the following

$project = new Project();
$project->fill($projectData);

But that will fail because of the relationships a Project has. What would be the best way to convert this data back into a Model?

Thanks

Please sign in or create an account to participate in this conversation.