Skip to content
Advertisement

Laravel 8: How to insert unique data from the DB

I need to insert some unique content into the DB using Laravel 8. Here is my code:

foreach($trigger as $e)
{
    if(is_array($e))
    {
        foreach($e as $t)
        $query = DB::table('tickets')->insert([
            'userId' => '',
            'types' => '',
            'startRound' => '',
            'endRound' => '',
            'numbers' => '0x'.$t->toHex() // MUST BE UNIQUE
        ]);
    }
}

As you can see the field numbers should stored unique numbers but I have some duplicated Hex values and I don’t want to store them at the DB.

So how can I insert UNIQUE values into the DB.

Note that I have already added unique() to the Migration like this:

$table->string('numbers')->unique();

But this does not solve my problem, I need some codes to be added to the Controller for making this field unique.

So I would really appreciate any idea or solution from you guys…

Thanks in advance.

UPDATE #1:

enter image description here

UPDATE #2:

enter image description here

UPDATE #3:

enter image description here

Advertisement

Answer

First you need to get details of existing data and then before inserting you need to check if the data already exists else insert.

$existing_data = DB::table('tickets')->pluck('numbers', 'numbers');

foreach($trigger as $e)
{
    if(is_array($e))
    {
        foreach($e as $t) {
            if(!isset($existing_data['0x'.$t->toHex()])) {
                $query = DB::table('tickets')->insert([
                        'userId' => '',
                        'types' => '',
                        'startRound' => '',
                        'endRound' => '',
                        'numbers' => '0x'.$t->toHex() // MUST BE UNIQUE
                ]);
                $existing_data['0x'.$t->toHex()] = '0x'.$t->toHex();
            }
        }
    }
}

To reduce the number of rows in $existing_data, you can pass all the values of $t in your $trigger by fetching them through some built-in function and then passing them to the query like this

$existing_data = DB::table('tickets')->whereIn('numbers', $all_values_of_t)->pluck('numbers', 'numbers');
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement