This article was originally written by https://www.honeybadger.io/blog/laravel-tdd/#authorDetails on the https://www.honeybadger.io/blog/laravel-tdd/. In this tutorial, I’ll show you how to get started with test-driven development in Laravel by creating a project from scratch.

Then, add the code that pushes an item to the cart: push('cart', [ 'id' => request('id'), 'qty' => 1, // default qty ]); return redirect('/cart'); }}

Update the store() method to include the code for checking for an existing item ID: // app/Http/Controllers/CartController.php public function store() { $existing = collect(session('cart'))->first(function ($row, $key) { return $row['id'] == request('id'); }); if (!$existing) { session()->push('cart', [ 'id' => request('id'), 'qty' => 1, ]); } return redirect('/cart'); }

Route::patch('/cart/{id}', [CartController::class, 'update']); Then, update the controller so that it finds the item passed in the request and updates their quantity: // app/Http/Controllers/CartController.php public function update() { $id = request('id'); $qty = request('qty'); $items = collect(session('cart'))->map(function ($row) use ($id, $qty) { if ($row['id'] == $id) { return ['id' => $row['id'], 'qty' => $qty]; } return $row; })->toArray(); session(['cart' => $items]); return redirect('/cart'); }
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners