2016-05-08 74 views
0

我想上傳公共文件夾中的多個文件和數據庫中的多個文件路徑,我能夠上傳公共文件夾中的多個文件,但我不能在數據庫中保存多個文件路徑。只有一個文件名和路徑被存儲在數據庫中。如何在laravel中保存多個文件上傳路徑到數據庫?

在查看

<form class="form-horizontal row-border" action="<?= URL::to('/checkiou') ?>" method="post" enctype="multipart/form-data"> 
<input type="hidden" name="_token" value="{{ csrf_token() }}"> 
<input type="file" name="attachments[]" multiple/> 
<input name="save" type="submit" value="Save"> 

控制器

public function upload() { 

     // Request the file input named 'attachments' 

    // Request the file input named 'attachments' 
     $files = Request::file('attachments'); 

     //If the array is not empty 
     if ($files[0] != '') { 
     foreach($files as $file) { 
    // Set the destination path 
     $destinationPath = 'uploads'; 
    // Get the orginal filname or create the filename of your choice 
     $filename = $file->getClientOriginalName(); 
    // Copy the file in our upload folder 
     $file->move($destinationPath, $filename); 
    } 

$data1 = DB::table('tbl_iou')->max('iou_id'); 
     $check=0; 
     $check=DB::table('tbl_iou') 
       ->where('iou_id',$data1) 
      ->update(array('image_path'=>$destinationPath, 'file_name'=>$filename)); 

     if ($check > 0) 
     { 
      $_SESSION['msg']="Petty cash details saved Successfully"; 
      return Redirect::to('iou_accounts'); 
     } 
    } 

回答

0

首先你執行的代碼,你想插入數據到數據庫中,foreach循環之外的第二部分。所以你只更新一次最後一個文件。其次,您的$data1變量存儲只有最大(假設是最後一個)iou_idtbl_iou表中。而在代碼:

$check=DB::table('tbl_iou') 
    ->where('iou_id',$data1) 
    ->update(array(
     'image_path'=>$destinationPath, 
     'file_name'=>$filename 
    )); 

您搜索排在那裏這iou_id是equeal到最後,讓你的只有一行更新值,與表的最大iou_id

我建議以下方法來解決這個問題。我假設你的數據庫表中有自動生成的iou_id,你只能插入新的行,而不是更新。

public function upload() { 
     // Request the file input named 'attachments' 

     // Request the file input named 'attachments' 
     $files = Request::file('attachments'); 
     //If the array is not empty 
     if (!empty($files[0])) { 
      $filesData = array(); 
      foreach($files as $file) { 
       // Set the destination path 
       $destinationPath = 'testuploads'; 
       // Get the orginal filname or create the filename of your choice 
       $filename = $file->getClientOriginalName(); 
       // Copy the file in our upload folder 
       $file->move($destinationPath, $filename); 

       // ADD DATA TO TEMPORARY ARRAY 
       $filesData[] = array('image_path'=>$destinationPath, 'file_name'=>$filename); 
      } 

      if(DB::table('tbl_iou')->insert($filesData)){ 
       $_SESSION['msg']="Petty cash details saved Successfully"; 
       return Redirect::to('iou_accounts'); 
      } 
     } 
    } 
相關問題