我有导入功能从我的产品表中的csv文件导入数据,我得到了成功的结果但没有导入我的数据库。
public function import(Request $request) {
//
$this->validate($request,[
'file' => 'required|mimes:csv,txt',
]);
if(($handle = fopen($_FILES['file']['tmp_name'],"r")) !== FALSE) {
fgetcsv($handle); //remove first row of excel file such as title
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$product = new Product;
$product->title = $data[0];
$product->slug = $data[1];
$product->imageOne = $data[2];
$product->imageTwo = $data[3];
$product->short_description = $data[4];
$product->description = $data[5];
$product->price = $data[6];
$product->meta_description = $data[7];
$product->meta_tags = $data[8];
// Other fields...
$product->created_at = Carbon::now()->format('Y-m-d H:i:s');
$product->updated_at = Carbon::now()->format('Y-m-d H:i:s');
$product->save();
}
fclose($handle);
}
Session::flash('success', 'Your products imported successfully.');
return redirect()->back();
}
路线
Route::post('import_products', 'ProductController@import')->name('import_products');
形式
<form action="{{route('import_products')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="input-group">
<input type="file" class="form-control" name="file">
<div class="input-group-btn">
<!-- Buttons -->
<button class="btn btn-success" type="submit"><i class="fa fa-upload"></i> Upload</button>
</div>
</div>
</form>
我的表格结构
任何想法?
答案 0 :(得分:1)
您可能需要考虑安装此库。
http://www.maatwebsite.nl/laravel-excel/docs/import
它完美地适用于我的几个项目。
Excel::load($request->file('file'), function($reader) {
$results = $reader->all();
$results->each(function($row) {
//code to model here...
});