-1

I want to make custom id using haruncpi/laravel-id-generator packages. I have 2 data that will insert into database. the program is work but the id of those data is duplicate

here is code

class ArtisSeeder extends Seeder
{
    public function CustomId() 
    {
        $config = [
            'table' => 'artis', 
            'field' => 'kd_artis',
            'length' => 4, 
            'prefix' => 'A'
        ];

        return IdGenerator::generate($config);
    }

    public function run()
    {
        DB::table('artis')->insert([
            [
                'kd_artis' => $this->CustomId(),
                'nm_artis' => 'ROBERT DOWNEY',
                'jk' => 'PRIA',
                'bayaran' => 10000000000,
                'award' => 2,
                'negara' => 'AS',
            ], 
            [
                'kd_artis' => $this->CustomId(),
                'nm_artis' => 'ANGELINA JOLIE',
                'jk' => 'WANITA',
                'bayaran' => 700000000,
                'award' => 1,
                'negara' => 'AS',
            ], 
        ]);
    }
}

note : kd_artis is the id.

So how to make the id not duplicate?

eglease
  • 2,445
  • 11
  • 18
  • 28

1 Answers1

0

You can save and manage much more easily through Eloquent. Use like this in Seeder:

Artis::insert([
    [
        'nm_artis' => 'ROBERT DOWNEY',
        'jk' => 'PRIA',
        'bayaran' => 10000000000,
        'award' => 2,
        'negara' => 'AS',
    ],
    [
        'nm_artis' => 'ANGELINA JOLIE',
        'jk' => 'WANITA',
        'bayaran' => 700000000,
        'award' => 1,
        'negara' => 'AS',
    ],
]);

Don't forget to include this in your Model. You can customize it according to you:

public static function boot()
{
    parent::boot();
    self::creating(function ($model) {
        $model->kd_artis = IdGenerator::generate([
            'table' => $this->table,
            'field' => 'kd_artis',
            'length' => 4,
            'prefix' => 'A',
        ]);
    });
}
cengsemihsahin
  • 921
  • 2
  • 8
  • 21