How To Optimize Laravel Code Eloquently With UpdateOrCreate()


In beginning of my Laravel learning, I did write more lines of code to perform my task than I write now. I started learning to adopt more eloquent ways of coding for Laravel encourages us to write. One simple task I performed by writing this many number of lines:

$place = PlaceModel::where('id', "132")->first();
  $place->update(['name' => 'Place Name', 'address' => 'Place Address',]);
  $place = PlaceModel::create([
    'name' => 'Place Name',
    'address' => 'Place Address',

This many lines of code can be optimised to single statement of line in Laravel Eloquent way. This is ome of the ways to optimize eloquent query on Laravel:

$place = PlaceModel::updateOrCreate(
    ‘id’ => ‘132’
    ‘name’ => ‘Place Name’,
    ‘address’ => ‘Place Address’,

In eloquent method updateOrCreate, first argument of array is used on where query to find the entry. If entry is found then it mass updates exisiting entry with values in second argument of array. If entry is not found then it creates new entry with values provided in second arguments of array. Make sure you have fillable fields declared in model class for mass update or mass create.

Laravel provides such other eloquent ways for us to optimise like firstOrCreate, firstOrFail etc. These methods lets us perform tasks in single statement withought going through multiple hoops. Code becomes clean and concise.

You might also like: HTTPS not working on AWS Elastic Beanstalk

You might also like: AWS Elastic Beanstalk Swap Environment Urls

You might also like: Adding two numbers in macOS x86-64 Assembly - Part 2

More Articles

Recommended posts