php - Why aren't my Eloquent models saving after upgrading to Laravel 8?

Need some help getting out of the weeds. I have host a Laravel application that started with 4.2 forever ago, that I upgrade every couple years and hop versions. I am a .NET developer by day but continue to maintenance this application. Anyway...

I upgraded from Laravel 6.x to 8.x, and started using Docker. I deployed everything to my production environment and most things were working. I did some light testing and admittedly I don't have tests for everything but some random parts of code aren't actually saving records to the database. It's SUPER odd. I've been troubleshooting for a few days and this is where I've landed at this point:

  1. Laravel 8
  2. MariaDB
  3. Laravel Sail hosting development environment
  4. Tinker lets me created/updated/delete records without issue using Eloquent
  5. Some things are saving in the production environment (this is using MySql)

You're probably wondering about the database difference, I am using a M1 Mac and there isn't M1 support for MySql Docker images yet. From my understanding, Mariadb is a drop-in replacement.

Here is the code I wrote tonight trying to simplify some of this really old spaghetti code I wrote like 6-7 years ago... it's not much better right now, but please go easy on me. Ultimately, it's just 4 arrays coming in from an Angular frontend that I'm iterating through and creating/updating records and then passing everything back to the browser.

What I can't figure out is that it all says it saves, it increments the PKs in the tables in the database and I get the fully formed models back with the newly assigned PKs... but it just doesn't save in the database. All of the failure is completely silent, I've found no logs, no issues while debugging with xdebug in vscode, no sql logs, the Eloquent model says it's successful whether it's create/update. Yes, nothing seems to be saving.

But I can take all of the exact same data and run it in tinker and it saves perfectly fine... I'm truly stumped on what I'm missing. And before 400 people respond about the $primaryKey property in my eloquent model class, I've most definitely already checked these a million times (or at least that's what it feels like right now).

/**
     * Replaces UploadInvoice()
     * Saves from editing an invoice.
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function saveApiInvoice(Request $request): JsonResponse
    {
        $result = new OpResult();
        DB::beginTransaction();

        try {
            $this->deletePendingInvoiceItems($request['pendingDeletes']);
            $sales = $this->saveSaleRecords($request)->getData();
            $overrides = $this->saveOverrideRecords($request)->getData();
            $expenses = $this->saveExpenseRecords($request)->getData();

            $payroll = $this->savePayrollInfo($request, $sales, $overrides, $expenses)->getData();

            $this->paystubService->processPaystubJob($request['issueDate']);

            return $result->setData([
                'sales' => $sales,
                'overrides' => $overrides,
                'expenses' => $expenses,
                'payroll' => $payroll
            ])->getResponse();
            
        } catch (\Exception $ex) {
            DB::rollBack();

            return $result->setToFail($ex)
                ->getResponse();
        }
    }

private function savePayrollInfo($request, $sales, $overrides, $expenses)
    {
        $result = new OpResult();
        $total = 0;

        foreach ($sales as $sale) {
            $total += $sale['amount'];
        }

        foreach ($overrides as $override) {
            $total += $override['total'];
        }

        foreach ($expenses as $expense) {
            $total += $expense['amount'];
        }

        $payroll = Payroll::agentId($request['agentid'])
            ->vendor($request['vendorId'])
            ->payDate($request['issueDate'])
            ->first();

        if ($payroll != null) {
            $payroll->amount = $total;
        } else {
            $agent = Employee::find($request['agentid']);

            $payroll = new Payroll([
                'agent_id' => $request['agentId'],
                'agent_name' => $agent != null ? $agent->name : '',
                'amount' => $total,
                'is_paid' => false,
                'vendor_id' => $request['vendorId'],
                'pay_date' => $request['issueDate']
            ]);
        }

        $saved = $payroll->save();

        return $result->setStatus($saved)
            ->setDataOnSuccess($payroll);
    }

    private function saveExpenseRecords($request)
    {
        $result = new OpResult();
        $expenses = [];

        foreach ($request['expenses'] as $e) {
            $expense = new Expense([
                'vendor_id' => $request['vendorId'],
                'type' => $e['type'],
                'notes' => $e['notes'],
                'amount' => is_numeric($e['amount']) ? $e['amount'] + 0 : 0,
                'agentid' => $request['agentId'],
                'issue_date' => $request['issueDate'],
                'wkending' => $request['weekending']
            ]);

            $save_success = $expense->save();

            if ($save_success) {
                $expenses[] = $expense;
            }
        }

        return $result->setDataOnSuccess($expenses);
    }

    private function saveOverrideRecords($request)
    {
        $result = new OpResult();
        $overrides = [];

        foreach ($request['overrides'] as $o) {
            $override = new Override([
                'vendor_id' => $request['vendorId'],
                'name' => $o['name'],
                'sales' => $o['sales'],
                'commission' => is_numeric($o['commission']) ? $o['commission'] + 0 : 0,
                'total' => is_numeric($o['total']) ? $o['total'] + 0 : 0,
                'agentid' => $request['agentId'],
                'issue_date' => $request['issueDate'],
                'wkending' => $request['weekending']
            ]);

            $save_success = $override->save();

            if ($save_success) {
                $overrides[] = $override;
            }
        }

        return $result->setDataOnSuccess($overrides);
    }

    private function saveSaleRecords($request)
    {
        $result = new OpResult();

        $sales = [];
        foreach ($request['sales'] as $invoice) {
            $sale = new Invoice([
                'vendor' => $request['vendorId'],
                'sale_date' => Carbon::parse($invoice['saleDate'])->format('Y-m-d'),
                'first_name' => $invoice['firstName'],
                'last_name' => $invoice['lastName'],
                'address' => $invoice['address'],
                'city' => $invoice['city'],
                'status' => $invoice['status'],
                'amount' => is_numeric($invoice['amount']) ? $invoice['amount'] + 0 : 0,
                'agentid' => $request['agentId'],
                'issue_date' => $request['issueDate'],
                'wkending' => $request['weekending']
            ]);

            $save_success = $sale->save();

            if ($save_success) {
                $sales[] = $sale;
            }
        }

        return $result->setDataOnSuccess($sales);
    }
    
    private function deletePendingInvoiceItems($pending_deletes)
    {
        if (isset($pending_deletes['sales']) && count($pending_deletes['sales']) > 0) {
            Invoice::destroy($pending_deletes['sales']);
            $sales_ids = [];
            foreach ($pending_deletes['sales'] as $key => $value) {
                $sales_ids[] = $value['invoiceId'];
            }

            DB::table('invoices')->whereIn('invoice_id', $sales_ids)->delete();
        }

        if (isset($pending_deletes['overrides']) && count($pending_deletes['overrides']) > 0) {
            $override_ids = [];
            foreach ($pending_deletes['overrides'] as $key => $value) {
                $override_ids[] = $value['overrideId'];
            }

            DB::table('overrides')->whereIn('ovrid', $override_ids)->delete();
        }

        if (isset($pending_deletes['expenses']) && count($pending_deletes['expenses']) > 0) {
            $expense_ids = [];
            foreach ($pending_deletes['expenses'] as $key => $value) {
                $expense_ids[] = $value['expenseId'];
            }

            DB::table('expenses')->whereIn('expid', $expense_ids)->delete();
        }
    }```

Answer

Solution:

You need to commit your DB transaction by adding DB::commit(); just at the end of your try{} block in saveApiInvoice() function, before returning results.

public function saveApiInvoice(Request $request): JsonResponse
    {
        $result = new OpResult();
        DB::beginTransaction();

        try {
            $this->deletePendingInvoiceItems($request['pendingDeletes']);
            $sales = $this->saveSaleRecords($request)->getData();
            $overrides = $this->saveOverrideRecords($request)->getData();
            $expenses = $this->saveExpenseRecords($request)->getData();

            $payroll = $this->savePayrollInfo($request, $sales, $overrides, $expenses)->getData();

            $this->paystubService->processPaystubJob($request['issueDate']);

            DB::commit(); // <--- Missing commit

            return $result->setData([
                'sales' => $sales,
                'overrides' => $overrides,
                'expenses' => $expenses,
                'payroll' => $payroll
            ])->getResponse();
            
        } catch (\Exception $ex) {
            DB::rollBack();

            return $result->setToFail($ex)
                ->getResponse();
        }
    }

Source