Update or Create

If you need to check if the record exists, and then update it, or create a new record otherwise, you can do it in one sentence - use Eloquent method updateOrCreate():

1// Instead of this
2$flight = Flight::where('departure', 'Oakland')
3 ->where('destination', 'San Diego')
4 ->first();
5if ($flight) {
6 $flight->update(['price' => 99, 'discounted' => 1]);
7} else {
8 $flight = Flight::create([
9 'departure' => 'Oakland',
10 'destination' => 'San Diego',
11 'price' => 99,
12 'discounted' => 1
13 ]);
14}
15// Do it in ONE sentence
16$flight = Flight::updateOrCreate(
17 ['departure' => 'Oakland', 'destination' => 'San Diego'],
18 ['price' => 99, 'discounted' => 1]
19);

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord