Laravel Check if value if so then update else create record

Laravel 5.8 check if value exist in table and if it then update otherwise create record.

Laravel has define some method to make this situation work.Lets see one by one.

We have firstOrCreatefirstOrNew

which is sued to create model data.firstOrCreate  method will check if data exist in a table using given column/pair and if data is not found then a new record will be inserted.

firstOrNew method like firstOrCreate  will check record in the database matching the given attributes.If not found instance of new model is returned that you can use to make make data save using save().


Like firstOrCreate and firstOrNew laravel have updateOrCreate method which work in same way.

personally i like updateOrCreate most.

User::updateOrCreate(['email' => $email],['name'=> "test",'age'=> 20,]);

Here first array key value pair define the conditions by which you will check and second array define the value you want to update.

Categories: PHP Tags: #Laravel,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.