0
点赞
收藏
分享

微信扫一扫

laravel批量插入, Maatwebsite\Excel上传获取数据

laravel批量插入

之前有人说laravel没有批量插入,是不对的,不仅有,而且很简单:
Elequent方法:

$res = User::insert($data);

DB方法:

$res = \DB::table('user)->insert($data);

下面演示一下从excel上传批量插入数据:

use Maatwebsite\Excel\Facades\Excel;
use Validator;
....

/**
* 读取用户上传的excel文件
* @param Request $request [description]
* @return [type] [description]
*/
public function readExcelOnly(Request $request)
{
$validator = Validator::make($request->all(), [
'file' => 'required|file|max:3072',
]);
if ($validator->fails()) {
$first_error = $validator->errors()->first();
return $this->outPutJson('', 201, $first_error);
}
$file = $request->file('file');
//获取文件后缀,必须是xls,xlsx类型,excel类型比较复杂,不能使用laravel的mimes或者mimetypes判断
$ext = $file->getClientOriginalExtension();
if (!in_array($ext, ['xlsx', 'xls'])) {
return $this->outPutJson('', 201, '必须是excel文件!');
}
$data = Excel::toArray(new FormDataImport(), $file);
#如果需要批量插入,请调用下面的方法
// $this->batchInserFormData($data[0]);
return $this->outPutJson($data);
}

laravel批量插入, Maatwebsite\Excel上传获取数据_json


举报

相关推荐

0 条评论