In this post, we will explain about Laravel Eloquent updateOrCreate() method and its importance in our code. It’s very common that we have database operations in our application, like inserting customer details and updating that customer details in a later stage, or deleting customer details.
For example, you have a function that is responsible for creating a user if he is not existing or updating the user details if he is existing.
Let’s see how we can achieve that in Laravel.
For this example, we have set the email address as a unique field.
$email = '[email protected]'; $phone = '909090900'; $city = 'New York'; $user = User::where('email', $email)->first(); if(is_null($user)) { // creates the user User::create([ 'email' => $email, 'phone' => $phone, 'city' => $city ]); } else { $user->update([ 'phone' => $phone, 'city' => $city ]); }
So far we have done what we have to do to achieve insert/update a user record. Indeed, it’s not a bad solution, but if we have an option for the more elegant solution, would you pick that?.
Laravel has an elegant method to deal with this situation and that’s the function updateOrCreate(). This function takes the first parameter as the select condition as an array and the second parameter as values that need to be updated as an array.
$user = User::updateOrCreate([ 'email' => $email ], [ 'phone' => $phone', 'city' => $city ]); print_r($user);
Please let us know if you have any comments.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply