x69 x69 - 3 months ago 93
MySQL Question

PHP Laravel : How to Avoid duplicate data while importing xl/ csv into mysql?

I want to import a csv file into database where name should always unique means if any duplicate title found it should avoid the row and go to the next row.
How do I implement using Laravel Controller?

Here's the controller for importing csv/xl I've used :

public function importExcel()
{
if(Input::hasFile('import_file')){
$path = Input::file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = ['title' => $value->title, 'description' => $value->description];
}
if(!empty($insert)){
DB::table('items')->insert($insert);
// dd('Insert Record successfully.');
}
}
}
return back();
}

Answer

Some improvement on Matt Borja's answer. This will also check earlier data from table.

public function importExcel()
{
    // Get current data from items table
    $titles = Item::lists('title')->toArray();

    if(Input::hasFile('import_file')){
        $path = Input::file('import_file')->getRealPath();
        $data = Excel::load($path, function($reader) {
        })->get();

        if(!empty($data) && $data->count()){
            $insert = array();

            foreach ($data as $key => $value) {
                // Skip title previously added using in_array
                if (in_array($value->title, $titles))
                    continue;

                $insert[] = ['title' => $value->title, 'description' => $value->description];

                // Add new title to array
                $titles[] = $value->title;
            }

            if(!empty($insert)){
                DB::table('items')->insert($insert);
              //  dd('Insert Record successfully.');
            }
        }
    }
    return back();    
}
Comments