Php 在laravel中上载时如何验证csv文件?
我使用的是laravel framework 5.2。我正在使用Maatwebsite Excel软件包,我已成功安装并成功导入CSV格式文件,但问题是: 假设我有一个表,列是:Php 在laravel中上载时如何验证csv文件?,php,mysql,laravel-5.2,maatwebsite-excel,Php,Mysql,Laravel 5.2,Maatwebsite Excel,我使用的是laravel framework 5.2。我正在使用Maatwebsite Excel软件包,我已成功安装并成功导入CSV格式文件,但问题是: 假设我有一个表,列是: Table_name:- employees_schedule columns:- user_id, customer_name, date, 现在,当我上传带有三列的CSV文件(用户id、客户名称、日期)时,它已成功上传 当我上传CSV格式文件时,带有附加列示例(用户id、客户名称、日期、黑客列、时间)我需
Table_name:- employees_schedule
columns:- user_id, customer_name, date,
现在,当我上传带有三列的CSV文件(用户id、客户名称、日期)
时,它已成功上传
当我上传CSV格式文件时,带有附加列示例(用户id、客户名称、日期、黑客列、时间)
我需要显示一条错误消息,比如“您的CSV文件有一些不需要的列”
有人能帮我吗。这是我的功能
public function UploadSchedule (Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
//echo "<pre>"; print_r($data); die;
Excel::load(Input::file('schedule'), function ($reader) {
$reader->each(function ($sheet) {
EmployeeSchedule::firstOrCreate($sheet->toArray());
});
});
return redirect()
->back()
->with(
'flash_message_success',
'Your Employee Schedule Uploaded successfully!'
);
}
}
公共函数上载计划(请求$Request)
{
如果($request->isMethod('post')){
$data=$request->all();
//echo”“;print_r($data);die;
<form id="addForm" role="form" class="form-horizontal" method="post"
action="{{ url('admin/upload-employee-schedule') }}"
enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}"/>
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Upload Schedule:</label>
<div class="col-md-5">
<input type="file" id="csv" name="schedule">
</div>
</div>
</div>
<div class="form-actions right1 text-center">
<button id="check" class="btn green" type="submit">Submit</button>
</div>
</form>
Excel::load(输入::文件('schedule'),函数($reader){
$reader->each(功能($sheet){
EmployeeSchedule::firstOrCreate($sheet->toArray());
});
});
返回重定向()
->back()
->与(
“闪光信息成功”,
'您的员工日程已成功上载!'
);
}
}
和刀片文件:-
public function UploadSchedule(Request $request){
if($request->isMethod('post')){
$data = $request->all();
$file = Input::file('schedule');
$handle = fopen($file,"r");
$header = fgetcsv($handle, 0, ',');
$countheader= count($header);
if($countheader<4 && in_array('user_id',$header) && in_array('customer_name',$header) && in_array('date',$header)){
Excel::load($file ,function($reader){
$reader->each(function($sheet){
$sheet['date'] = date('Y-m-d',strtotime($sheet['date']));
EmployeeSchedule::firstOrCreate($sheet->toArray());
});
});
} else {
return redirect()->back()->with('flash_message_error', 'Your CSV files having unmatched Columns to our database...Your columns must be in this sequence <strong> user_id,customer_name,date </strong> only');
}
return redirect()->back()->with('flash_message_success', 'Your Employee Schedule Uploaded successfully!');
上载时间表:
提交
在这里,我找到了自己的解决方案。我只需打开文件并获得第一个标题行。以下是我的片段:-
public function uploadSchedule(Request $request)
{
// Validate request
$request->validate([
'import_file' => 'required|mimes:csv,txt',
]);
$data = $this->fetchCsv($request); // Fetch the CSV data
$headerRow = $data->first()->keys()->toArray(); // Fetch the header row
$validate = $this->validateHeaderRow($headerRow); // Filter it through our validation
// If our header row passed validation
if( $validate == true )
{
// Load $data into array if > 0
if($data->count()){
$arr = $this->loadCsvIntoArray($data, $request);
// Write to the database
if(!empty($arr)){
EmployeeSchedule::insert($arr);
}
}
}
// Return our import finished message
$message = $this->returnMessage($validate, $request);
return $message;
}
公共函数上载计划(请求$Request){
如果($request->isMethod('post')){
$data=$request->all();
$file=Input::file('schedule');
$handle=fopen($file,“r”);
$header=fgetcsv($handle,0,',');
$countheader=计数($header);
if($countheadereach)(函数($sheet){
$sheet['date']=日期('Y-m-d',标准时间($sheet['date']);
EmployeeSchedule::firstOrCreate($sheet->toArray());
});
});
}否则{
return redirect()->back()->带有('flash_message_error',您的CSV文件的列与我们的数据库不匹配…您的列必须按此顺序用户id、客户名称、日期仅限];
}
return redirect()->back()->带有('flash_message_success','Your Employee Schedule uplated successfully!');
}您还可以查看以下url
我知道这是一条老线索,但我认为值得重温。希望它能帮助一些可怜的人解决这个问题。你可以用 (拉威尔5.7) 您的函数正在做很多事情-您应该将验证和加载函数分开。这将使它更容易测试 例如:
// Return a schedule CSV
public function fetchCsv($request)
{
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path)->get();
return $data;
}
fetchCSV():
public function validateHeaderRow($headerRow)
{
$validate = false;
if( $headerRow[0] == 'user_id'
&& $headerRow[1] == 'customer_name'
&& $headerRow[2] == 'date' )
{
$validate = true;
}
return $validate;
}
// Load the import .CSV data into an array
public function loadCsvIntoArray($data, $request)
{
foreach ($data as $key => $value) {
$arr[] = [
'user_id' => $value->user_id,
'customer_name' => $value->customer_name,
'date' => $value->date,
];
}
return $arr;
}
// Fetch our message to display to user after import
public function returnMessage($validate, $request)
{
if( $validate == true )
{
return back()->with('success', 'Schedule uploaded successfully!');
} else {
return back()->with('danger', 'Your .CSV headers do not meet the requirements. Must be: `user_id`, `customer_name`, `date`');
}
}
验证headerRow($headerRow):
public function validateHeaderRow($headerRow)
{
$validate = false;
if( $headerRow[0] == 'user_id'
&& $headerRow[1] == 'customer_name'
&& $headerRow[2] == 'date' )
{
$validate = true;
}
return $validate;
}
// Load the import .CSV data into an array
public function loadCsvIntoArray($data, $request)
{
foreach ($data as $key => $value) {
$arr[] = [
'user_id' => $value->user_id,
'customer_name' => $value->customer_name,
'date' => $value->date,
];
}
return $arr;
}
// Fetch our message to display to user after import
public function returnMessage($validate, $request)
{
if( $validate == true )
{
return back()->with('success', 'Schedule uploaded successfully!');
} else {
return back()->with('danger', 'Your .CSV headers do not meet the requirements. Must be: `user_id`, `customer_name`, `date`');
}
}
loadCsvIntoArray($data$request):
public function validateHeaderRow($headerRow)
{
$validate = false;
if( $headerRow[0] == 'user_id'
&& $headerRow[1] == 'customer_name'
&& $headerRow[2] == 'date' )
{
$validate = true;
}
return $validate;
}
// Load the import .CSV data into an array
public function loadCsvIntoArray($data, $request)
{
foreach ($data as $key => $value) {
$arr[] = [
'user_id' => $value->user_id,
'customer_name' => $value->customer_name,
'date' => $value->date,
];
}
return $arr;
}
// Fetch our message to display to user after import
public function returnMessage($validate, $request)
{
if( $validate == true )
{
return back()->with('success', 'Schedule uploaded successfully!');
} else {
return back()->with('danger', 'Your .CSV headers do not meet the requirements. Must be: `user_id`, `customer_name`, `date`');
}
}
returnMessage($validate$request):
public function validateHeaderRow($headerRow)
{
$validate = false;
if( $headerRow[0] == 'user_id'
&& $headerRow[1] == 'customer_name'
&& $headerRow[2] == 'date' )
{
$validate = true;
}
return $validate;
}
// Load the import .CSV data into an array
public function loadCsvIntoArray($data, $request)
{
foreach ($data as $key => $value) {
$arr[] = [
'user_id' => $value->user_id,
'customer_name' => $value->customer_name,
'date' => $value->date,
];
}
return $arr;
}
// Fetch our message to display to user after import
public function returnMessage($validate, $request)
{
if( $validate == true )
{
return back()->with('success', 'Schedule uploaded successfully!');
} else {
return back()->with('danger', 'Your .CSV headers do not meet the requirements. Must be: `user_id`, `customer_name`, `date`');
}
}
请在答案中添加相关信息。由于链接可能会过期,这个答案在将来可能会变得多余