Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

JuanDMeGon/Laravel-from-Scratch

17 stars
3 code files
View JuanDMeGon/Laravel-from-Scratch on GitHub

app/Cart.php

Open in GitHub
use App\Product;
use Illuminate\Database\Eloquent\Model;
 
class Cart extends Model
{
//
public function products()
{
return $this->morphToMany(Product::class, 'productable')->withPivot('quantity');
}
//
}

app/Product.php

Open in GitHub
use App\Cart;
use Illuminate\Database\Eloquent\Model;
 
class Product extends Model
{
//
public function carts()
{
return $this->morphedByMany(Cart::class, 'productable')->withPivot('quantity');
}
//
}

app/Http/Controllers/OrderController.php

Open in GitHub
use App\Services\CartService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
 
class OrderController extends Controller
{
public $cartService;
 
public function __construct(CartService $cartService)
{
$this->cartService = $cartService;
 
$this->middleware('auth');
}
//
public function store(Request $request)
{
return DB::transaction(function() use($request) {
$user = $request->user();
 
$order = $user->orders()->create([
'status' => 'pending',
]);
 
$cart = $this->cartService->getFromCookie();
 
$cartProductsWithQuantity = $cart
->products
->mapWithKeys(function ($product) {
$quantity = $product->pivot->quantity;
 
if ($product->stock < $quantity) {
throw ValidationException::withMessages([
'cart' => "There is not enough stock for the quantity you required of {$product->title}",
]);
}
 
$product->decrement('stock', $quantity);
$element[$product->id] = ['quantity' => $quantity];
 
return $element;
});
 
$order->products()->attach($cartProductsWithQuantity->toArray());
 
return redirect()->route('orders.payments.create', ['order' => $order->id]);
}, 5);
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.