1

I am getting undefined array key error. but I cant see where the problem is.

below is my controller code. I am storing data into files[] array.

        if ($request->file('files')){
        foreach($request->file('files') as $key => $file)
        {
            $fileName = $complaint->election_id.'_'. $complaint->id.'_'.$key.'.'.$file->extension();      
            $description = $file->getClientOriginalName();   

            $file->storeAs('complaints', $fileName); 
            
            $files[]['filename'] = $fileName;  
            $files[]['description'] = $description;       

        }
    }

The array seems okay because when I dump the array i get this.

array:4 [
  0 => array:1 [
    "filename" => "2_50_0.pdf"
  ]
  1 => array:1 [
    "description" => "sample pdf.pdf"
  ]
  2 => array:1 [
    "filename" => "2_50_1.png"
  ]
  3 => array:1 [
    "description" => "sample profile image 2.png"
  ]
]

enter image description here

then I loop through this array to store the data into my model.

foreach ($files as $file) {
            $complaintEvidence = new ComplaintEvidence();
            $complaintEvidence->filename = $file['filename'];
            $complaintEvidence->description = $file['description'];
            $complaintEvidence->save();
        }

And I get undefined array key error on this line $complaintEvidence->description = $file['description'];

enter image description here

i dont understand where the issue is. The filename line of code works perfectly fine.

How do i fix this?

Bashabi
  • 696
  • 1
  • 12
  • 40
  • 3
    `$file['description']` does not exist in the first subarray, and `$file['filename']` doesn't exist in the 2nd one. – GrumpyCrouton Aug 23 '23 at 14:34
  • 6
    $files[]['filename'] = $fileName; $files[]['description'] = $description; instead of this use $files[]=[ 'filename'=> $fileName, 'description'=>$description ]; – John Lobo Aug 23 '23 at 14:35

1 Answers1

4

It seems you are creating your $files array incorrectly.

This code creates a new array entry for each key, so filename and description both get their own array, but you want them combined.

$files[]['filename'] = $fileName;  
$files[]['description'] = $description; 

So instead, do this

$files[] = [
   'filename' => $fileName,
   'description' => $description
]; 

Which will result in an array like this

array:2 [
  0 => array:2 [
    "filename" => "2_50_0.pdf",
    "description" => "sample pdf.pdf"
  ]
  1 => array:2 [
    "filename" => "2_50_1.png",
    "description" => "sample profile image 2.png"
  ]
]
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71