PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
238: Building a Multi-Vendor Marketplace Backend
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:
- Groups the items in the cart by their
vendor_id. - For each group, creates a record in a
sub_orderstable. - Links each
sub_orderto the mainorderId. - Calculates the
sub_totalfor that specific vendor. - Returns an array of the created
sub_orderIDs.
Constraint: Ensure that your logic prevents the creation of duplicate sub-orders for the same vendor within a single master order.
There are no comments for now.