Why INSERT sometimes insert empty record instead of filling them out?

I have a table in a db where users add data constantly, now from this table I take some columns and do INSERT in a second db ('mysql2') :: connection, I use student_id to not allow it to have a dublicated record ne db2. But my problem is that sometimes INSERT puts empty data in db2, I do not know why this happens but in the table of db1 the data is filled in while in db2 sometimes the data passes "" (empty).

Use a cronjob to execute every minute as the data is updated every moment

$data = DB::connection('mysql2')
    ->where('status', '=', 'Y')

foreach ($data as $key => $aStudent) {
    // Check if student_id duplicated
    $existing_data_in = DB::table('student')
        ->where("student_id", $aStudent->student_id)

    if (! $existing_data_in) {
            "first_name"        =>$aStudent->first_name,
            "last_name"         =>$aStudent->last_name,
            "age"               =>$aStudent->age,
            "student_id"        =>$aStudent->student_id,
            "created_at"        =>$aStudent->created_at

Log::info('Success, Data Updated');

Or maybe should I run cronjob rarely? My problem is when some record on table1 are filed with data and when this record goes to table2 are empty on table2. If I check same student_id on table1 is okay but on table2 are saved empty

i have loged my query on cronjob and this is what i get in case i find an empty filed on table 2. So last name on table 1 in this case is filled with really last name but on table 2 is inserted as empty and this is query (what hapend)

[2022-01-19 14:16:17] local.INFO: select `student_id` `first_name`, `last_name`, `age`, `created_at` from `students` where `student_id` = ? limit 1 [421] 

// this comes from query where i check for dublicated lines i think
[2022-01-19 14:16:17] local.INFO: select * from `student` where `student_id` = ? limit 1 [421] 

[2022-01-19 14:16:17] local.INFO: insert into `student` 
(`student_id`, `first_name`, `last_name`, `age`, `created_at`) values 
(?, ?, ?, ?, ?) 
["421","name","","38","2022-01-19 14:13:35"]  

Iam using laravel 6.X version

1 answer

  • answered 2022-01-19 16:53 Juni

    To simplify your code, you can use updateOrCreate or firstOrNew, something like this:





    as I see that key value of array you are passing to create are same, you can simply pass $aStudent.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum