Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I don't understand why I am getting undefined array key exception error – Laravel 9 PHP 8

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"
  ]
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading