将CSV导入数据库Laravel

时间:2017-10-08 21:01:59

标签: php database laravel csv upload

我正在使用Laravel 5.3 尝试将Csv文件上传到数据库。 Csv标题和数据库字段是相同的。文件上传到服务器没有问题,但我无法将数据导入数据库。我究竟做错了什么?它表示CSV导入成功但数据库中没有任何内容。感谢

function postImport( Request $request)
{

    if(!is_null($request->file('fileimport')))
    {
        $file =     $request->file('fileimport');
        $filename = $file->getClientOriginalName();
        $uploadSuccess = $file->move('./uploads/' , $filename );
        if( $uploadSuccess ) {
            $csv = array_map('str_getcsv', file('./uploads/'.$filename));
            $table = $this->info['config']['grid'];
            $fields = array();
            foreach($table as $f )
            {
                $fields[] = $f['field'];
            }
            //print_r($fields);
            foreach($csv as $row) {
                $data = array();
                foreach($fields as $key=>$val)
                {
                    if($key != 0 )
                        $data[$val] = (isset($row[$key]) ? $row[$key] : '' ) ;  
                }
                //print_r($data);
                //echo $row[0];
                $this->model->insertRow($data ,$row[0]);    

            }

            return response()->json(array('status'  => 'success','message'=>'Csv Imported Successfully !'));              
        } else {
            return response()->json(array('status'  => 'error','message'=>'Upload Failed!'));   
        }
    } else {            
        return response()->json(array('status'  => 'error','message'=>'Please select file to Upload!'));
    }   

}

1 个答案:

答案 0 :(得分:0)

试试这样。使用 $(document).ready(function(){ var checkScrollBar = function(){ $('.bg-dark').css({ backgroundColor: $(this).scrollTop() > 1 ? 'rgb(0, 0, 0)' : 'transparent' }) } $(window).on('load resize scroll', checkScrollBar) }); 填充array_push数组

fields