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

DoppyWoppy's avatar

Laravel Query

I want to build a query in laravel from the given SQL query.

 select 
if(count(*) = 0, 'insert', if(count(*) = 1, 'update', if(count(*) > 1, 'multiple records found', 
    'nothing'))) as required_action 
    from 
      test_importer 
     where 1 
       and record_id = 1881 
       and date_time = "1999-21-19 22:33:18";
0 likes
5 replies
jlrdw's avatar

There are countless examples on the forum already of "building up a query", search first, study examples in docs, and then show what you tried, if you still can't get it.

1 like
jestins's avatar

DB::raw("IF(count(*) = 0, 'insert', 'update') as required_action"),

DoppyWoppy's avatar
DoppyWoppy
OP
Best Answer
Level 1

This one helped me.

$users = DB::select('select if(count(*) = 0, \'insert\', if(count(*) = 1, 
\'update\', if(count(*) > 1, \'multiple\', \'nothing\'))) as required_action from 
test_importer where record_id = ? and date_time = ? ',
[$row['record_id'],$row['date_time']]);
jlrdw's avatar

updateOrCreate

You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():

// If there's a flight from Oakland to San Diego, set the price to $99. // If no matching model exists, create one. $flight = App\Flight::updateOrCreate( ['departure' => 'Oakland', 'destination' => 'San Diego'], ['price' => 99] );

Please or to participate in this conversation.