//common to both
$exists['name'] => $voter_arr['name'];
// add parameter depending on condition
if (someCondition) {
$exists['phone'] => $voter_arr['phone'];
} elseif (otherCondition) {
$exists['email'] => $voter_arr['email'];
}
$base_voter_rec = Base_voter::updateOrCreate($exists, $voter_arr);
May 19, 2018
10
Level 1
Laravel updateOrCreate 'OR' condition check
Currently am performing updateOrCreate with one condition
$base_voter_rec = Base_voter::updateOrCreate(
['voter_id' => $voter_arr['voter_id']],
$voter_arr
);
Now, How can I perform updateOrCreate with 'OR' case similar like passing array.
I wan't something likle: ['name' => $voter_arr['name'], 'phone' => $voter_arr['phone]] OR ['name' => $voter_arr['name'], 'email' => $voter_arr['email]]
$base_voter_rec = Base_voter::updateOrCreate(
['name' => $voter_arr['name'], 'phone' => $voter_arr['phone]],
$voter_arr
);
How can I achieve this?
Level 67
In that case, you can't really do that with updateOrCreate. You'd have to do it manually using parameter grouping in the where clause
Something like
$existing = Base_voter::where('name', $voter_arr['name'])
->where(function($query) {
$query->where('phone', $voter_arr['phone']);
$query->orWhere('email', $voter_arr['email']);
})->first();
// select * from base_voters where `name` = 'someName' and (`phone` = 'somePhone' or `email` = 'someEmail')
if ($existing) {
// do an update on $existing
$existing->fill($voter_arr);
} else {
// create new one
Base_voter::create($voter_arr);
}
Please or to participate in this conversation.