1

So, i'm using Laravel and PostgreSQL in my project and I wanna import the data to the database from my .csv file. I wrote this piece of code so far:

<?php
use Illuminate\Database\Seeder;
use League\Csv\Reader;

class MigracaoBaseUsuarioSeeder extends Seeder{
    public function run()
    {
        $usedData = [];
        $file = database_path().'/seeds/csv/migracao/base_usuario.csv';
        $csv = Reader::createFromPath($file);
        $csv->setOffset(1);

        $nbInsert = $csv->each(function ($row)  {
            // return false if there is no data
            if ( empty($row)) return false;
            \DB::table('users')->insert(
                array(
                    'id' => $row[0],
                    'password' => bcrypt($row[7]),
                    'is_superuser' => $row[3],
                    'username' => $row[4],
                    'email' => $row[7],
                    'is_staff' => $row[8],
                    'is_active' => $row[9],
                    'created_at' => $row[10],
                    'nome' => $row[11],
                    'cpf' => $row[12],
                    'rg' => $row[13],
                    'telefone' => $row[14],
                    'comprovante' => $row[15],
                    'tipo_usuario' => $row[16],
                    'instituicao_formadora_id' => $row[17],
                    'municipio_id' => $row[18],
                    'declaracao' => $row[19],
                    'gestor' => $row[20],
                )
            );
            return TRUE; // if return is FALSE, iteration will stop
        });
    }
}

The problem occurs only when some of these columns are empty, such as "instituicao_formadora_id".

When I run this code, I receive an error:

[PDOException]                                                               
  SQLSTATE[22P02]: Invalid text representation: 7 ERRO:  input sintax is invalid for integer: ""

In my .csv file I have something like:

info,info,info,info,,info

So, how can I skip the null values?

  • If(!isset()) should do the trick – Andreas Jul 24 '17 at 21:13
  • Think this has to be a dupe of 'check for/ handle null values'. You likely want to change the null state to an accepted value, integer zero or empty string. – ficuscr Jul 24 '17 at 21:14
  • Depending on the size of the file, how often this data will be imported and whether you have permission, it may be worth looking at the [`COPY`](https://www.postgresql.org/docs/9.2/static/sql-copy.html) statement in Postgres. – Jacob Mulquin Jul 24 '17 at 22:02

0 Answers0