Skip to Content
Course content

238: Building a Multi-Vendor Marketplace Backend

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this exact scenario play out in dozens of freelance projects. You're building a marketplace, you've got your roles set up, and you're feeling good because you've implemented a check to ensure only vendors can edit products. But then, a savvy user realizes they can change a product ID in the URL and suddenly they're editing their competitor's pricing. This is a classic Insecure Direct Object Reference (IDOR) bug, and it's a nightmare for any marketplace backend.

// The "Dangerous" Way
public function updateProduct(Request $request, $productId) {
    $user = Auth::user();

    // The mistake: checking the ROLE, but not the OWNERSHIP
    if ($user->role !== 'vendor') {
        abort(403, 'Only vendors can edit products.');
    }

    $product = Product::find($productId);
    $product->update($request->all());
    
    return response()->json(['message' => 'Product updated!']);
}

Stopping the Cross-Vendor Edit

The problem here is that the code asks, "Are you a vendor?" but it fails to ask, "Are you the vendor who actually owns this product?" In a multi-vendor system, your permissions must be granular. You aren't just checking a user's level; you're checking their relationship to the data.

To fix this, we need to bake the ownership check directly into the query. Instead of finding the product and then updating it, we look for the product where the ID matches AND the vendor_id matches the current user's ID. If the query returns nothing, it means either the product doesn't exist or the vendor is trying to touch something they don't own.

// The Secure Way
public function updateProduct(Request $request, $productId) {
    $user = Auth::user();

    if ($user->role !== 'vendor') {
        abort(403, 'Vendor access required.');
    }

    // We scope the search to the specific vendor
    $product = Product::where('id', $productId)
                      ->where('vendor_id', $user->id)
                      ->first();

    if (!$product) {
        // I prefer a 404 here so we don't even leak that the product exists
        abort(404, 'Product not found.');
    }

    $product->update($request->all());
    return response()->json(['message' => 'Product updated securely!']);
}

Handling the Multi-Vendor Order Split

Now that we've secured the products, we hit the biggest architectural hurdle: the Order. In a simple shop, one order = one payment. In a marketplace, one order might contain a lamp from Vendor A and a book from Vendor B. You can't just mark the whole order as "Shipped" because Vendor A might be fast while Vendor B is lagging.

The professional way to handle this is by introducing a sub_orders or order_items_group table. When a customer checks out, you create one master orders record for the payment transaction, but you immediately split that order into multiple sub-orders based on the vendor_id of the products.

  • Master Order: Tracks the total payment, customer details, and payment status.
  • Sub-Order: Tracks the specific items for one vendor, the shipping status for that vendor, and the vendor's payout amount.

I highly recommend this approach because it keeps your vendor dashboards clean. Vendor A should never see what the customer bought from Vendor B; they should only see their specific sub-order and the items they are responsible for fulfilling.

Calculating Marketplace Commissions

You aren't running a charity; you're running a platform. You need a way to take a cut. I usually implement this at the sub-order level. Instead of a flat fee, you can define a commission percentage in your vendors table, allowing you to charge "Premium Vendors" a lower rate if they pay a monthly subscription.

$commissionRate = $vendor->commission_rate; // e.g., 0.10 for 10%
$subOrderTotal = $items->sum('price');
$marketplaceFee = $subOrderTotal * $commissionRate;
$vendorPayout = $subOrderTotal - $marketplaceFee;

// Save these to your sub_order record so the audit trail is clear
$subOrder->update([
    'total' => $subOrderTotal,
    'commission' => $marketplaceFee,
    'payout_amount' => $vendorPayout
]);

By calculating this at the moment of order creation, you protect yourself from future changes to the commission rate affecting historical payout data. Always snapshot the fee at the time of sale.




📋 Practical Task

Build a Vendor-Specific Order Splitter Logic

You have a Cart object containing multiple items from different vendors. Your task is to write a PHP function splitOrderIntoSubOrders($orderId, $cartItems) that performs the following:

  1. Groups the items in the cart by their vendor_id.
  2. For each group, creates a record in a sub_orders table.
  3. Links each sub_order to the main orderId.
  4. Calculates the sub_total for that specific vendor.
  5. Returns an array of the created sub_order IDs.

Constraint: Ensure that your logic prevents the creation of duplicate sub-orders for the same vendor within a single master order.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.