Thursday, March 15, 2018

Laravel CSV file upload - development

Laravel CSV file upload

I am having trouble in the csv file import in laravel 5.5. Though insertion is done in the database but if i modify the same csv file by adding extra rows it doesnt get inserted. Below is the code that I am using in my Controller

public function uploadIndustries(Request $request){
    $this->validate($request, [
        'upload-file' => 'required|mimes:csv,txt'
    ]);
    $handle = fopen($_FILES['upload-file']['tmp_name'],"r");    
    fgetcsv($handle);  // remove first Row of the file
    while (($value = fgetcsv($handle, 10000, ";")) !== false) {
        if($value[0] !== "" || $value[1] !== "") {  
        if(IndustryAction::where('industry_name','=',$value[3])->first() === NULL) {
                $industryData = IndustryAction::firstOrCreate(
                    ['industry_name' => $value[3]], [
                    'prop_fname' => $value[0],
                    'prop_lname' => $value[1],
                    'industry_type' => $value[2], 
                    'industry_name' => $value[3],
                    'industry_address' => $value[4],
                    'district' => $value[5],
                    'pincode' => $value[6],
                    'category' => $value[7],
                    'establishment_year' => $value[8],
                    'last_renewal' => $value[9],
                    'next_renewal' => $value[10],
                    'contact' => $value[11],
                    'email' => $value[12],
                    'user_id' => Auth::user()->id,
                    'created_at' => now()->toDateTimeString(),
                    'updated_at' => now()->toDateTimeString(),
                ]);
                $industryData->save();
            } else {
                return back()->with('error', 'Similar Data Found - $value[3]');
            }
        }
    }
    if($industryData) {
        return back()->with('success', 'File Imported Successfully');
    } else {
        return back()->with('error', 'Oops!!! Something Went Wrong');
    }
}

So i want like; if i modify the csv by adding some extra rows then only those rows should be inserted in the database. No duplicate records and for that I am using the industry_name field as check parameter



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-csv-file-upload/
via Lzo Media

No comments:

Post a Comment