0

How do I get the last insert id, if I'm inserting it into the database using upsert?

  
        $student_db=DB::table('users')->upsert([
            [
                'cell_number' => $parent_cellnumber, 
                'password' => Hash::make(Str::random(24)), 
                'status' =>1,
                'role_id' =>10,
                'user_code'=>Str::random(24),
    
            ]
        ], ['cell_number'], ['cell_number']);
    
    
        //insert into another table
        
        $parent_id = $student_db->id;
   
Shuast
  • 15
  • 6

1 Answers1

0

I understand it might be too late, yet as of today laravel does not support returning id's from upserts, so here is a raw SQL that might be helpful (tested on Postgres, MySQL also supports the similar syntax)

    $sql = <<<EOL
        INSERT INTO table_name (...) VALUES (...)
        ON CONFLICT ON CONSTRAINT constraint_name
        DO UPDATE SET updated_at = now()
        RETURNING id
        EOL;

    return collect(DB::select($sql))
        ->pluck('id')
        ->toArray();
Majesty
  • 2,097
  • 5
  • 24
  • 55