phplaraveldingo-api

Laravel handle complicated request


I have a request that sends a FormData to my API.

It has following structure:

image: file type image;
text: 'some long string';
array: ['string', 'string'];
data: [
  { field: 'string', link: 'url' },
  { field: 'string', link: 'url' },
]

I successfully handled first three inputs but stuck with the last one.

Laravel receives it as an array of strings instead of an array of objects.

I'm not able to access fields neither via $request->data->field nor via $request->data['field'}

Also I tried to use json_decode but this returns null

Update #1

array(4) {
  ["text"]=>
  string(17) "asdajsklfsdnfnads"
  ["array"]=>
  array(2) {
    [0]=>
    string(6) "sadasd"
    [1]=>
    string(6) "safsdf"
  }
  ["data"]=>
  array(2) {
    [0]=>
    string(39) "{link: "http://sdf.sdf", field: "asfd"}"
    [1]=>
    string(44) "{link: "http://sdf.sasdf", field: "asasdfd"}"
  }
  ["image"]=>
  object(Illuminate\Http\UploadedFile)#787 (7) {

Solution

  • Try this code

    $result = [];
    foreach($request->data as $data) {
       $object = json_decode($data);
       $result[] = $object;
       // $object['filed'] you can access in field attribute 
    }
    
    dd($result);