lundi 18 avril 2016

Laravel 5 - Saved data overwritten

I am having an issue with data being overwritten. I have a Document Model and a DocumentData Model. A Document can have many DocumentData. So I have a data capture form, and in my create function if I output the request I get something like the following

array:8 [▼
  "_token" => "UHTN66xH4ChHpaxWAt4hWYFfpwUyjo6EunLp2iuV"
  "whatData" => "rgfterter"
  "whoData" => "tertertertert"
  "startDate" => "28-04-2016"
  "deliveryDate" => "30-04-2016"
  "whyData" => "wefrwerwe"
  "howData" => "rwerwerwer"
  "filePath" => array:2 [▼
    0 => UploadedFile {#30 ▼
      -test: false
      -originalName: "image.png"
      -mimeType: "image/png"
      -size: 788038
      -error: 0
    }
    1 => UploadedFile {#31 ▼
      -test: false
      -originalName: "image2.png"
      -mimeType: "image/png"
      -size: 1091127
      -error: 0
    }
  ]
]

What I then need to do is create a Document

$document = new Document();
$document->projectId = $project->id;
$document->name = 'Test Document';
$document->save();

And then do the documentData using the above data. DocumentData essentially has a key/value, where the key is the input label and the value is the inputted data. At the moment I am doing this

$documentData = new DocumentData();
$documentData->documentId = $document->id;

foreach ($inputs as $key => $value) {
    if($key !== '_token' && $key !== 'filePath') {
        $documentData->key = $key;
        $documentData->value = $value;
    }
    $documentData->save();
}

$fileString = "";
if (Input::hasFile('filePath')) {
    $files = Input::file('filePath');

    foreach($files as $file) {
        $file->move(public_path('uploads'), $file->getClientOriginalName());

        $fileString .= public_path('uploads') . '/' . $file->getClientOriginalName();
        $documentData->key = 'File Path';
        $documentData->value = $fileString;
        $documentData->save();
    }
}

The Document is created fine, but I am only getting one row for DocumentData - the last uploaded file path. So it appears that the other rows are being overwritten. How can I make sure all inputs are recorded correctly within my database?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire