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

Advertisements

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"
  ]
]

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'];

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"
  ]
]

Leave a ReplyCancel reply