Home > Blockchain >  Codeigniter 4 Multiple Image Upload Issue
Codeigniter 4 Multiple Image Upload Issue

Time:11-23

When I update the database, it uploads a single image. How do I upload multiple?


        $id = $this->request->getPost('id');
        
        $model = new UrunModel();
        $file = $this->request->getFile('resim');
        $resim_eski = $model->find($id);
        
        if($file->isValid() && !$file->hasMoved()){
        
        $eski_resim = $resim_eski['resim'];
        if(file_exists("dosyalar/uploads".$eski_resim)){
              unlink("dosyalar/uploads".$eski_resim);
        } 
        $imagename = $file->getRandomName();
        $file->move("dosyalar/uploads", $imagename);
        
        }else{
             $imagename = $resim_eski['resim'];
        }
        
        if ($this->request->getFileMultiple('images')) {
 
             foreach($this->request->getFileMultiple('images') as $res)
             {   
 
                $res->move(WRITEPATH . 'dosyalar/uploads');
             
        $data=[
        'baslik'          => $this->request->getPost('baslik'),
        'slug'            => mb_url_title($this->request->getPost('baslik'), '-', TRUE),
        'kisa_aciklama'   => $this->request->getPost('kisa_aciklama'),
        'kategori'        => $this->request->getPost('kategori'),
        'query_kategori'  => $this->request->getPost('query_kategori'),
        'aciklama'        => $this->request->getPost('aciklama'),
        'fiyat'           => $this->request->getPost('fiyat'),
        'indirimli_fiyat' => $this->request->getPost('indirimli_fiyat'),
        'resim'        => $imagename, 
        'resimler' =>  $res->getClientName(),
                'type'  => $res->getClientMimeType()
        ];
        
        
        $model -> update($id,$data);
        
        } 
        
        } 
        return redirect()->to(base_url('yonetim/urunler'));
        }


Controller code above, I've been struggling for 2 days, I couldn't manage it somehow. When I run the code, it just adds 1 image to each product. I want to add more than one image to 1 product for the gallery part. Any suggestions for this code or a different solution?

CodePudding user response:

        function add()
      {
        $length = count($_FILES['image']['name']);
        $filename = $_FILES['image']['name'];
        $tempname = $_FILES['image']['tmp_name'];

        $allimage = array();
        foreach($filename as $key =>$value)
        {
            move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'.$filename[$key]);
            $allimage[] = $filename[$key];
        }
        if(!empty($allimage))
        {
            $allimage = json_encode($allimage);
        }
        else
        {
            $allimage = '';
        }

        $data['image'] = $allimage;
        $this->db->insert('table',$data);  

        }
  • Related