Laravel create or update if already exsists. Upsert operations
In Laravel, you can use the updateOrInsert method to perform an upsert (update or insert) operation on the database. The method takes two arguments: an array of conditions to match a record in the table, and an array of values to update or insert if the record doesn’t exist.
Here’s an example of how you can use the updateOrInsert method to upsert a record in a “users” table:
User::updateOrInsert(
['email' => $request->input('email')],
[
'name' => $request->input('name'),
'password' => Hash::make($request->input('password')),
]
);
In this example, it will look for a record in the “users” table where the “email” column is equal to the value of the email input field in the request. If a matching record is found, it will update the “name” and “password” columns with the values from the request. If no matching record is found, it will insert a new record with the values from the request.
You could also use Eloquent models and updateOrCreate() method to achieve the same results as above.
User::updateOrCreate(
['email' => $request->input('email')],
[
'name' => $request->input('name'),
'password' => Hash::make($request->input('password')),
]
);
This will also update the existing record if it found with the attributes passed or insert if not.
Please note that, for this examples to work you should have user model and it should be referenced accordingly in the code.