octobercmsoctober-form-controller

Uploading multiple images in frontend - OctoberCMS


In the frontend form I have multiple file upload field. So on the form submit, I create a new record in the db and then try to attach multiple images to it, like so:

Relation for the gallery specified in the model class

public $attachMany = [
    'gallery' => 'System\Models\File',
];

Frontend form processing

function onCreate() {
    $data = post();
    
    $newRecord = Record::create($data);
    
    if (Input::hasFile('gallery')) {
        $newRecord->gallery()->create(['data' => Input::file('file_input')]);
    }
}

Frontend form HTML

<form method="POST" accept-charset="UTF-8"
      data-request="onCreate" data-request-files data-request-flash>

    <input accept="image/*" name="gallery" type="file" id="gallery" multiple>

</form>

However, I keep getting the following error:

SQLSTATE[HY000]: General error: 1364 Field 'disk_name' doesn't have a default value

Setting $guarded = [] in vendor/october/rain/src/Database/Attach/File.php did not help.


Solution

  • You would need array file field name gallery[] , to post multiple file and receive them at PHP side.

    // html changes 
    <input accept="image/*" name="gallery[]" type="file" id="gallery" multiple>
    //                      HERE       --^ make it array for multiple files 
    
    
    // PHP side
    // $newRecord = ...your code;
    if (Input::hasFile('gallery')) {
        foreach(Input::file('gallery') as $file) {
    
            $fileModel = new System\Models\File;
            $fileModel->data = $file;
            $fileModel->is_public = true;
            // $fileModel->save(); <- save only if you are adding new file to existing record
            // other wise let differ binding handle this 
           
            $newRecord->gallery()->add($fileModel); 
        }     
    }
    // $newRecord->save();   
    

    It should solve your issue.

    if any doubts please comment .