zakarialabib
1 week ago
206
2
General

Import Csv Data to database

Posted 1 week ago by zakarialabib

Hey guys i tried to import import csv data to my database,

public function importSubmit(Request $request) {

    $user = Auth::user();
    $package = $user->subscribes()->orderBy('id','desc')->first();
    $prods = $user->products()->orderBy('id','desc')->get()->count();
    if($prods < $package->allowed_products || $package->allowed_products == 0) {
    $log = "";
    //--- Validation Section
    $rules = [
        'csvfile'      => 'required|mimes:csv,txt',
    ];

    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails()) {
        return response()->json(array('errors' => $validator->getMessageBag()->toArray()));
    }

    $filename = '';
    if ($file = $request->file('csvfile'))
    {
        $filename = time().'-'.$file->getClientOriginalName();
        $file->move('assets/temp_files',$filename);
    }

    //$filename = $request->file('csvfile')->getClientOriginalName();
    //return response()->json($filename);
    $datas = "";

    $file = fopen(public_path('assets/temp_files/'.$filename),"r");
    $i = 1;
    while (($line = fgetcsv($file)) !== FALSE) {

        if($i != 1)
        {

        if (!Product::where('sku',$line[0])->exists()){

            //--- Validation Section Ends

            //--- Logic Section
            $data = new Product;
            $sign = Currency::where('is_default','=',1)->first();

            $input['type'] = '';
            $input['sku'] = $line[0];

            $input['category_id'] = "";
            $input['subcategory_id'] = "";
            $input['childcategory_id'] = "";

            $mcat = Category::where(DB::raw('lower(name)'), strtolower($line[1]));
            //$mcat = Category::where("name", $line[1]);

            if($mcat->exists()){
                $input['category_id'] = $mcat->first()->id;

                if($line[2] != ""){
                    $scat = Subcategory::where(DB::raw('lower(name)'), strtolower($line[2]));

                    if($scat->exists()) {
                        $input['subcategory_id'] = $scat->first()->id;
                    }
                }
                if($line[3] != ""){
                    $chcat = Childcategory::where(DB::raw('lower(name)'), strtolower($line[3]));

                    if($chcat->exists()) {
                        $input['childcategory_id'] = $chcat->first()->id;
                    }
                }



            $input['photo'] = $line[5];
            $input['name'] = $line[4];
            $input['details'] = $line[6];

// $input['category_id'] = $request->category_id; // $input['subcategory_id'] = $request->subcategory_id; // $input['childcategory_id'] = $request->childcategory_id; $input['color'] = $line[13]; $input['price'] = $line[7]; $input['previous_price'] = $line[8]; $input['stock'] = $line[9]; $input['size'] = $line[10]; $input['size_qty'] = $line[11]; $input['size_price'] = $line[12]; $input['youtube'] = $line[15]; $input['policy'] = $line[16]; $input['meta_tag'] = $line[17]; $input['meta_description'] = $line[18]; $input['tags'] = $line[14]; $input['product_type'] = $line[19]; $input['vendor_link'] = $line[20];

            // Conert Price According to Currency
            $input['price'] = ($input['price'] / $sign->value);
            $input['previous_price'] = ($input['previous_price'] / $sign->value);
            $input['user_id'] = $user->id;
            
            // Save Data
            $data->fill($input)->save();

            // Set SLug
            $prod = Product::find($data->id);
            $prod->slug = str_slug($data->name,'-').'-'.strtolower($data->sku);

            // Set Thumbnail
            $background = Image::canvas(300, 300);
            $resizedImage = Image::make($line[5])->resize(300, 300, function ($c) {
                $c->aspectRatio();
                $c->upsize();
            });

            // insert resized image centered into background
            $background->insert($resizedImage, 'center');
            // save or do whatever you like
            $thumbnail = time().str_random(8).'.jpg';
            $background->save(public_path().'/assets/images/thumbnails/'.$thumbnail);
            $prod->thumbnail  = $thumbnail;
            $prod->update();


            }else{
                $log .= "<br>Row No: ".$i." - No Category Found!<br>";
            }

        }else{
            $log .= "<br>Row No: ".$i." - Duplicate Product Code!<br>";
        }

        }

        $i++;

    }
    fclose($file);


    //--- Redirect Section
    $msg = 'Bulk Product File Imported Successfully.<a href="'.route('admin-prod-index').'">View Product Lists.</a>'.$log;
    return response()->json($msg);



    }
    else
    {
        //--- Redirect Section
        return response()->json(array('errors' => [ 0 => 'You Can\'t Add More Products.']));

        //--- Redirect Section Ends
    }
}

Please sign in or create an account to participate in this conversation.