In this tutorial, we will explore laravel updateOrCreate and firstOrCreate methods in detail.
UpdateOrCreate
The updateOrCreate eloquent method is mainly used when we either want to update the record or create the record upon some criterias. Lets take a quick example for this:
Suppose, we have a setting module with key and value pair. Everytime when we update , we don’t want to write the logic to fetch the setting and update its value but we can do the following easily:
Setting::updateOrCreate([
'key' => "company_name"
],[
'value' => "Code Dailly"
])
Here updateOrCreate method take 2 parameters the first array is the key-value pair of the column and value that we want to check and the second one is the value that we want to update.
In short, above code searches in Setting model with key “company_name”, if it finds the record it will update the value else it will create a new record with that key and value.
firstOrCreate
Similar to updateOrCreate , firstOrCreate() eloquent method helps us to retrieve or create the record on the basis of criteria.
Lets take an above example, if we want to either get or create the record on the basis key =>company_name, then we can use this method.
Setting::firstOrCreate([
'key' => "company_name"
],[
'value' => "Code Dailly"
])
So, this method first try to find the record with key company_name and if it find the record it will return that else it will create a new record.

