2

I am using laravel framework 5.2. I am using Maatwebsite Excel package i have succesfully installed and succesfully imported CSV format files but problem is:

Suppose i have one table and columns are:

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

Now when i upload CSV file with three columns (user_id, customer_name, date) it is successfully upload.

When I upload CSV format file, with additional columns example (user_id, customer_name, date, hacking_column, time) I need to show an error message, something like "Your CSV files has some unwanted columns"

Can anyone help me. Here is my function

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

And blade file:-

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

2 Answers 2

2

Here i found the solution of my own. I just open the file and get the first header row. here is my snippet:-

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

}

Sign up to request clarification or add additional context in comments.

Comments

1

I know this is an old thread, but I thought it was worth revisiting. Hopefully it helps some poor soul parsing SO with this exact problem. You can use Maatwebsite/Excel 2.1.0 for this

(Laravel 5.7) Your function is doing a lot of things - you should separate the validation and loading functions. Will make it way easier to test.

For example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.