Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Čamo's avatar
Level 3

Database insert with where conditions

I find a code which look like:

DB::table('customer_active_logs')
     ->where('customer_id', $customer->id)
     ->where('updated_at', '>', $today)  // Every day make new log
     ->insert(['customer_id' => $customer->id, 'created_at' => $now, 'updated_at' => $now]);

I dont understand it. Does this code really work? What the where conditions doing with insert? What is this really doing? Can somebody explain it to me?

0 likes
2 replies
tykus's avatar

It is nonsense; the where Builder methods have zero effect; as such, they are not used in the resulting SQL. Conceptually, they are wrong anyway, you're inserting a new record, no constraint applies.

DB::table('customer_active_logs')->insert([
    'customer_id' => $customer->id,
    'created_at' => $now,
    'updated_at' => $now
]);
1 like
amitsolanki24_'s avatar
$is_customer_active_logs_exists = DB::table('customer_active_logs')
     ->where('customer_id', $customer->id)
     ->where('updated_at', '>', $today)->exists();  // Every day make new log
     if(!$is_customer_active_logs_exists){
 DB::table('customer_active_logs')->insert(['customer_id' => $customer->id, 'created_at' => $now, 'updated_at' => $now]);
}
1 like

Please or to participate in this conversation.