Home > Back-end >  MUltile file upload in laravel
MUltile file upload in laravel

Time:07-12

public function store(StoreWorkerRequest $request)
{
    $attributes = $request->validated();

    $worker = DB::transaction(function () use ($attributes, $request) {
        $worker = Worker::create($attributes);
        $course = $worker->course()->create(['course_name' => $attributes['course_name']]);
        $medical_data = $worker->medical_detail()->create(['expiry_date' => $attributes['expiry_date']]);
        $document = $worker->document()->create(['doc_name' => $attributes['doc_name']]);
        if($request->file('doc_files' || 'media_files' || 'user_files'))
        {
            foreach($request->file('doc_files') as $image)
            {
                $document = $document->media()->create(["filename" => 
          fileUpload($image, 'Course'),"filetype" => "pdf"]);
            }
        foreach($request->file('media_files') as $image)
            {
                $course = $course->media()->create(["filename" => 
               fileUpload($image, 'Course'),"filetype" => "pdf"]);
            }
          foreach($request->file('user_files') as $image)
            {
                $media = $user->media()->create(["filename" => 
            fileUpload($image, 'Course'),"filetype" => "pdf"]);
            }
        }
        return $worker;
    });

This is my multiple file upload in laravel, But the problem in, I have three fields that have multiple file (media_files, doc_files, user_files). Problem in Icannot repleat the same foreach llop for every files_attributes. (like i cannt heck if($request->file('doc_file')) for media_files user _files, repeating the same foreach lopp again and again. How can I optimize this code?)

CodePudding user response:

You should be able to loop over $request->file() and perform your upload based on that:

foreach($request->file() as $key => $files) {
  foreach ($files as $image) {
    if ($key == 'media_files') {
      $course->media()->create(['filename' => fileUpload($image, 'Course'), 'filetype' => 'pdf']);
    } elseif ($key == 'doc_files') {
      $document->media()->create(['filename' => fileUpload($image, 'Course'), 'filetype' => 'pdf']);
    } elseif ($key == 'user_files') {
      $user->media()->create(['filename' =>  fileUpload($image, 'Course'), 'filetype' => 'pdf']);
    }   
  }
}

You may need to use 'doc_file' instead of 'doc_files' depending on if your names are singular or plural, but the approach should still work.

  • Related