Skip to content

Expert Answers to Your Magento, Shopify & Shopware Questions

Vendor-neutral, engineer-written explanations. Clear definitions first, then practical steps with real examples — no fluff.

Stagebit builds and maintains stores on Magento, Adobe Commerce, Shopify, Shopware, and Laravel, and this library holds the questions our own engineers get asked most often on each platform.

How do I sync orders from a Laravel app into an ERP without losing any?

SB
Written by Stagebit Engineering Team
Updated November 2026 7 min read Verified by engineers

To sync orders from a Laravel app to an ERP without losing any, make your database the record of what has been sent. The queue only delivers jobs, and jobs can fail, vanish, or run twice. No setup is perfect, but you can make gaps visible and recoverable from your own records.

Quick answer

In Laravel, save each order and an outbox row in the same database transaction, then dispatch a queued job after the commit. Have the job send the order to the ERP with a stable idempotency key, so retries never create duplicates. Retry temporary errors with backoff, and flag permanent ones for review on the outbox row. A scheduled command then re-sends anything still unconfirmed.

Why Laravel orders go missing before they reach the ERP

Orders go missing at five points in a Laravel ERP integration.

  • The app commits the order and then crashes, or the queue backend is down, before the job is pushed. The order exists, but no job does.
  • A job dispatched inside a transaction can run before the commit. According to Laravel’s queue documentation, a worker can process the job first, so the order may not exist yet.
  • The job runs out of attempts. Laravel attempts a job once by default, so a single ERP timeout can fail it.
  • The ERP processes the request, but the response never arrives. The retry then creates a duplicate order.
  • Nobody notices. A stopped worker or an ERP validation error leaves orders unsynced with no alert.

Six steps to sync Laravel orders to an ERP reliably

Diagram of a Laravel ERP order sync: outbox row, queued job, ERP, and a reconciliation loop that re-sends unconfirmed orders.

Step 1: Write an outbox row with every order

Create an outbox table with one row per order event, such as order created or order cancelled. Make the order ID and event type unique together, so one event never gets two rows. For events that can repeat, such as order updates, add a version number to that key. Each row also stores an attempt count, the last error message, the ERP’s reference, and a synced-at timestamp. The status column uses four values:

StatusMeaningWhat happens next
pendingSaved and waiting, or between retriesA queue worker sends it to the ERP
syncedThe ERP confirmed the orderNothing further
failedRetries ran out on a temporary errorReconciliation re-dispatches it after a cooldown
needs_reviewThe ERP rejected the data permanentlyA person fixes the data, then re-dispatches the row

Insert the row inside the same transaction that saves the order, as the snippet shows. This is the transactional outbox pattern, a general design that works in any framework. Both writes succeed or fail together, so no order exists without a record of its pending sync.

DB::transaction(function () use ($data) {
    $order = Order::create($data);

    $sync = ErpOrderSync::create([
        'order_id' => $order->id,
        'event'    => 'order_created',
        'status'   => 'pending',
    ]);

    SyncOrderToErp::dispatch($sync->id, $order->id)->afterCommit();
});

Step 2: Dispatch after the commit

The snippet chains afterCommit() onto the dispatch. Laravel then waits for the open transaction to commit before pushing the job, and discards the job if the transaction rolls back. You can also set after_commit to true on the queue connection. Treat the dispatch as a speed boost. The outbox row is the guarantee, so a failed push only delays the order until Step 5.

Step 3: Make the ERP write idempotent and safe to overlap

Send a stable key on every ERP request, such as the outbox row ID, in an idempotency header. The row ID stays the same across retries of one event, and it differs between a create and a cancel. The ERP must enforce that key for it to work. If it cannot, ask whether it supports a unique external order reference, or look the reference up before creating the order.

Do not rely on ShouldBeUnique for this. It stops duplicate jobs from sitting in the queue at once, and its lock releases when the job finishes or exhausts its attempts. It does not stop a later duplicate ERP write.

Add the WithoutOverlapping middleware keyed on the order ID, so a cancellation never runs alongside the creation of the same order. Give it an expiry, so a crashed worker cannot hold the lock forever. Then allow more than one attempt. A released job still consumes an attempt, and with the default of one try, an overlapping job is never retried.

Overlap protection does not guarantee order. The job therefore also checks that earlier events for the same order are synced, and releases itself if they are not. An earlier event stuck in needs_review holds later events until someone resolves it. That is intended.

Skip HTTP-level retries inside the job. The HTTP client’s retry() method retries client errors as well as server errors, so a permanent 422 would repeat. Stacked retries also multiply attempts and can outlive the job timeout, which defaults to 60 seconds. Set a short HTTP timeout instead, and let the queue own the retries.

Step 4: Retry temporary errors and fail permanent ones

Set a retry window, a backoff schedule, and a timeout on the job. The 13.x docs use attributes, as the snippet shows. Older versions use properties. For an unstable ERP API, add the ThrottlesExceptions middleware, so repeated errors pause the job. Laravel’s docs suggest pairing it with time-based attempts, which is why the snippet uses a retry window instead of a fixed tries count.

Throw a custom exception for errors that retries cannot fix, such as a 400 or 422 validation response, and list it in the FailOnException middleware. The job then fails at once. Treat 401 and 403 as temporary. An expired credential affects every order, so it should raise an alert instead of pushing each order to needs_review.

The failed() method updates the outbox row either way: needs_review for permanent errors, and failed when retries run out. Keep the status on the outbox row. Laravel can prune failed jobs, so the failed jobs table is a poor long-term record.

// Imports omitted. In Laravel 11+, use Illuminate\Foundation\Queue\Queueable, which includes dispatch() and release().
#[RetryFor(hours: 6)]
#[Backoff([60, 300, 900, 1800])]
#[Timeout(30)]
class SyncOrderToErp implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $syncId, public int $orderId) {}

    public function middleware(): array
    {
        return [
            (new WithoutOverlapping((string) $this->orderId))->releaseAfter(60)->expireAfter(180),
            new ThrottlesExceptions(10, 5 * 60),
            new FailOnException([PermanentErpException::class]),
        ];
    }

    public function handle(): void
    {
        $sync = ErpOrderSync::with('order')->findOrFail($this->syncId);

        if ($sync->status === 'synced') {
            return;
        }

        $blocked = ErpOrderSync::where('order_id', $sync->order_id)
            ->where('id', '<', $sync->id)
            ->where('status', '!=', 'synced')
            ->exists();

        if ($blocked) {
            $this->release(60);

            return;
        }

        $sync->increment('attempts');

        $response = Http::withToken(config('services.erp.token'))
            ->withHeaders(['Idempotency-Key' => 'order-sync-'.$sync->id])
            ->timeout(10)
            ->post(config('services.erp.url').'/orders', $sync->order->toErpPayload());

        if (in_array($response->status(), [400, 422])) {
            throw new PermanentErpException($response->body());
        }

        $response->throw();

        $sync->update([
            'status'        => 'synced',
            'erp_reference' => $response->json('id'),
            'synced_at'     => now(),
            'last_error'    => null,
        ]);
    }

    public function failed(Throwable $e): void
    {
        ErpOrderSync::find($this->syncId)?->update([
            'status'     => $e instanceof PermanentErpException ? 'needs_review' : 'failed',
            'last_error' => $e->getMessage(),
        ]);
    }
}

Step 5: Reconcile on a schedule

Schedule an Artisan command that re-dispatches two groups. The first is pending rows with no attempts after a few minutes, which means the dispatch was lost. The second is failed rows, once a cooldown has passed. Set that cooldown longer than your longest backoff delay, so reconciliation does not duplicate a job that is still waiting to retry. Cap total attempts so an unfixable order stops cycling, and skip needs_review rows entirely.

Choose the other thresholds by asking how long an unsynced order can wait before it causes harm. A missed warehouse cut-off is one example.

// routes/console.php
Schedule::command('erp:reconcile')
    ->everyFiveMinutes()
    ->withoutOverlapping()
    ->onOneServer();

// In the command's handle() method. Thresholds are examples.
ErpOrderSync::query()
    ->where('attempts', '<', 20)
    ->where(function ($query) {
        $query->where(fn ($q) => $q->where('status', 'pending')
                ->where('attempts', 0)
                ->where('created_at', '<', now()->subMinutes(5)))
            ->orWhere(fn ($q) => $q->where('status', 'failed')
                ->where('updated_at', '<', now()->subMinutes(60)));
    })
    ->each(fn ($sync) => SyncOrderToErp::dispatch($sync->id, $sync->order_id));

Also run a slower check against the ERP itself. Compare each day’s synced order count in your database with the ERP’s count. Alert on any difference. An order can be rejected or deleted inside the ERP after you marked it synced. A lost response can also leave the opposite gap, where the ERP holds the order and your row still says pending.

Step 6: Monitor workers and stuck rows

Keep queue workers running under a process monitor such as Supervisor. If you run Redis queues, Laravel Horizon adds a dashboard and worker configuration on top. Alert when any row stays pending past your threshold, and when the failed or needs_review count rises above zero. Watch the table, since it is your source of truth. Horizon cannot show an order whose job was never pushed.

Give support staff a small admin view of failed and needs_review rows, with a retry button that re-dispatches the job. For failed jobs in the queue itself, use php artisan queue:failed to inspect them and php artisan queue:retry to re-run them. Fix the cause first, or the jobs will fail again.

Trade-offs of this approach

  • It adds a table, a command, and a schedule to maintain. That cost buys an auditable sync.
  • The design delivers each order at least once, so duplicates are possible by design. The ERP-side idempotency in Step 3 is what makes that safe.
  • If the ERP has no external reference field and no lookup endpoint, a narrow race remains between the check and the create. Plan a periodic duplicate report in that case.
  • Laravel’s failover queue driver can switch to a second connection when the primary is down. It narrows the gap, but the outbox still covers what it misses.
  • A direct HTTP call inside the checkout request is simpler. It also ties checkout speed and success to the ERP being available.

Where to start with a Laravel ERP order sync

If you can only build three parts first, build the outbox table, the idempotency key, and the reconciliation command. The first two make retries safe, and the third finds what the queue missed. Add overlap protection, backoff tuning, and monitoring next. If you want a team to design the outbox, field mapping, and reconciliation for your Laravel ERP integration, see our Laravel development services.

Was this answer helpful?

Your feedback helps us improve our answers.

Still need help?

Orders going missing between Laravel and your ERP?

If you're weighing how to make your order sync recoverable, or chasing orders that never reached the ERP, we're happy to walk through your queue setup and your options.

Talk to Laravel Experts