Home > Blockchain >  why when import excel, my data I added is not saved to the database used laravel
why when import excel, my data I added is not saved to the database used laravel

Time:11-17

why when import excel, my data I added is not saved to the database ? i import excel with type xlsx

My controller

public function importDataPegawai(Request $request)
{
    Excel::import(new ImportPegawai, $request->file('upload-pegawai'));
    return redirect('dashboard-admin')->with('success','Berhasil Upload Data Pegawai');
}

My Import

<?php

namespace App\Imports;

use App\Models\PegawaiModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Auth;
use DB;


class ImportPegawai implements ToModel, WithStartRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        foreach ($row as $data){
            $data = DB::table('tbl_pegawai')->where('nip', $row[0])->get();
            if (empty($data)) {
                return new PegawaiModel([
                    'nip'           => $row[0],
                    'nama_lengkap'  => $row[1],
                    'pangkat'       => $row[2],
                    'gol'           => $row[3],
                    'jabatan'       => $row[4],
                    'unit_kerja'    => $row[5]
                ]);
            }
        }
        
    }

    public function startRow(): int
    {
        return 3;
    }
}

When i dd($data) the result is like this

result dd

i got the data from my excel upload.

What's the problem ? why my data cannot save in the database

CodePudding user response:

This code will return an Collection, which is an object, objects are always not empty.

DB::table('tbl_pegawai')->where('nip', $row[0])->get();

If you switch to first() it will return a model or null, effectively doing what you intended to.

DB::table('tbl_pegawai')->where('nip', $row[0])->first();

CodePudding user response:

I have been in this situation before and figured that it can be caused by different factors. You might want to try the following:

  1. Save the file you're about to upload to Excel 97-2003 Workbook format first.
  2. Make sure the columns you're inserting data into is included in protected $fillable under App\PegawaiModel.
  3. If certain cells in your spreadsheet are empty, make a validation for it.

Ex.

if ($row[0] === null) { 
    $row = null;
}

or if it's a string column that's not nullable, you can do

if ($row[0] === null) { 
    $row = 'NO DATA'; 
}
  • Related