如何在laravel中上传时验证csv文件?

时间:2017-03-02 05:21:30

标签: php mysql laravel-5.2 maatwebsite-excel

我正在使用laravel框架5.2。我正在使用Maatwebsite Excel软件包我已经成功安装并成功导入了CSV格式文件,但问题是:

假设我有一个表和列是:

Table_name:- employees_schedule 
   columns:- user_id, customer_name, date,

现在当我上传包含三列(user_id, customer_name, date)的CSV文件时,它已成功上传。

当我上传CSV格式文件时,附加列示例(user_id, customer_name, date, hacking_column, time)我需要显示错误消息,例如“您的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!'
            );
    }
}

和刀片文件: -

<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>

3 个答案:

答案 0 :(得分:0)

在这里,我找到了自己的解决方案。我只是打开文件并获得第一个标题行。这是我的片段: -

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

}

答案 1 :(得分:0)

答案 2 :(得分:0)

我知道这是一个旧线程,但是我认为值得重新讨论。希望它可以帮助一些可怜的人解析这个确切的问题。您可以使用Maatwebsite/Excel 2.1.0 for this

(Laravel 5.7) 您的函数正在做很多事情-您应该将验证和加载函数分开。将使测试变得更容易。

例如:

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

fetchCSV():

// Return a schedule CSV
public function fetchCsv($request)
{
    $path = $request->file('import_file')->getRealPath();
    $data = Excel::load($path)->get();

    return $data;
}

validateHeaderRow($ headerRow):

public function validateHeaderRow($headerRow)
{
    $validate = false;

    if( $headerRow[0] == 'user_id'
        && $headerRow[1] == 'customer_name' 
        && $headerRow[2] == 'date' )

        {
            $validate = true;
        } 

    return $validate;

}

loadCsvIntoArray($ data,$ request):

// 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;
}

returnMessage($ validate,$ request):

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