Laravel 8.x – How to use updateOrCreate with a where clause?

  laravel, laravel-8, php

I am trying to use Laravel updateOrCreate to update a record if its within this month and last month based on if an ID exists.

            'id' => $request->get('id'),
            // where created_at is within the last 2 months
            'created_at' => [
            'discipline_one' => $request->get('d-one'),
            'discipline_two' => $request->get('d-two'),
            'discipline_three' => $request->get('d-three'),
            'discipline_four' => $request->get('d-four'),
            'discipline_five' => $request->get('d-five'),
            'discipline_six' => $request->get('d-six'),

If the ID exists, and the result is in this current month or last, a new record is created instead of updated.

Expected input: 1 (which exists from last month)
Expected output: Record is updated

Expected input: 2 (which doesn’t exist or is not within 2 months)
Expected output: New record is created

Source: Laravel

Leave a Reply