david001's avatar

Multiple file upload validation

How can validate multiple file before uploading


This is the code to upload multiple file,but i want to validate before upload
public function caseFileStore(FileValidationRequest $request)
    {    
        $files = [];
        foreach ($request->file('crFile') as $file) {
            if($file->isValid()) {
            $path = $file->store('public/files');

        $files [] = [
            'file_name' => $file->getClientOriginalName(),
            'file_path' => $path,
        
            'description'=>'something',
            'created_at' => $now = Carbon:: now()->format('Ymd H: i: s'),
            'updated_at' => $now,
        ];
    }
}

       File::insert($files);

FileValidationRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FileValidationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        'crFile' = > 'required |max: 2000|mimes:pdf,doc,docx,jpeg,jpg,png' 
    }
}

view:

<form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">{{ csrf_field() }}
                        <input type="file" name="crFile[]" class="">
                        <input type="file" name="crFile[]" class="">
                        <input type="file" name="crFile[]" class="">
                        <br><button type="submit" class="btn btn-default ">Upload File</button>
                    </form>
0 likes
2 replies
usamamuneer's avatar

You may do define allowed file extensions right in your controller and validate through those while uploading.

protected $allowedFileExtensions = [
        'png',
        'jpg',
        'gif',
    ];

A simple method for checking if the file is allowed

protected function isAllowedFile( UploadedFile $file ) {
        return in_array(
            $file->getClientOriginalExtension(),
            $this->allowedFileExtensions
        );
    }

Finally, where you're uploading files, simply

$this->isAllowedFile( $request->image );

this may do the trick, Good luck.

1 like

Please or to participate in this conversation.