如何在laravel中保存多个文件上传路径到数据库?

时间:2016-05-08 10:37:51

标签: file upload laravel-5.2

我想在公共文件夹和数据库中的多个文件路径上传多个文件,我可以在公共文件夹中上传多个文件,但我无法在db中保存多个文件路径。只有一个文件名和路径存储在数据库中。

视图中的

<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');
       }
  }

1 个答案:

答案 0 :(得分:0)

首先,您执行第二部分代码,在foreach循环之外,您要将数据插入数据库。因此,您只为最后一个文件更新一次。

其次,您的$data1变量仅存储iou_id表中的最大值(假设为最后一个)tbl_iou。在代码中:

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

您搜索的行iou_id是最后一个标记的行,因此您只更新了一行中的值,表中包含最大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');
            }
        }
    }