here is how you can use `firstOrNew()` with multiple conditions to check if a record exists in Laravel:
The `firstOrNew()` method allows you to check for the existence of a record based on multiple conditions. Here are a few examples:
php
// Check if a record exists based on email and name
$user = User::firstOrNew([
'email' => '
<script language='JavaScript' type='text/javascript'>
<!--
var prefix = 'mailto:';
var suffix = '';
var attribs = '';
var path = 'hr' + 'ef' + '=';
var addy47194 = 'example' + '@';
addy47194 = addy47194 + 'email' + '.' + 'com';
document.write( '<a ' + path + '\'' + prefix + addy47194 + suffix + '\'' + attribs + '>' );
document.write( addy47194 );
document.write( '<\/a>' );
//-->
</script><script language='JavaScript' type='text/javascript'>
<!--
document.write( '<span style=\'display: none;\'>' );
//-->
</script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
<script language='JavaScript' type='text/javascript'>
<!--
document.write( '</' );
document.write( 'span>' );
//-->
</script>',
'name' => 'John Doe'
]);
if ($user->exists) {
// Record exists
// You can now update the record if needed
$user->update([
'phone' => '123-456-7890'
]);
} else {
// Record does not exist
// You can now save the new record
$user->save();
}
php
// Check if a record exists based on multiple custom attributes
$product = Product::firstOrNew([
'uuid' => $uuid,
'category_id' => $categoryId
]);
if ($product->exists) {
// Record exists
// You can now update the record if needed
$product->update([
'name' => 'Updated Product Name'
]);
} else {
// Record does not exist
// You can now save the new record
$product->save();
}
The key points are:
1. Pass an array of conditions to the `firstOrNew()` method, with the column names as the keys and the values to match.
2. Check the `$model->exists` property to determine if the record already exists in the database.
3. If the record exists, you can update it as needed.
4. If the record does not exist, you can save the new record.
Using `firstOrNew()` with multiple conditions allows you to efficiently check for the existence of a record and perform the appropriate action (update or create) in a single method call, without having to write additional conditional logic.
Citations:[1] https://stackoverflow.com/questions/23720336/laravel-firstornew-with-multiple-conditions
[2] https://freek.dev/1087-breaking-laravels-firstorcreate-using-race-conditions
[3] https://laracasts.com/discuss/channels/laravel/laravel-firstorcreate-without-update
[4] https://laraveldaily.com/post/dont-check-record-exists-methods-orcreate-ornew
[5] https://github.com/laravel/framework/issues/42967