0

I've been trying to direct the add to cart button on the home page of the website(for online shopping) to the addtocart file and the shopping cart. I just can't seem to find what's wrong. Here are the codes.

home.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StyleSync Home Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <nav class="navbar">
        <div class="container">
            <div class="logo">
                <img src="logo_no_name.png" alt="Logo">
            </div>
            <ul class="nav-links">
                <li><a href="index.php">Home</a></li>
                <li><a href="shoppingcart.php">Shopping Cart</a></li>
                <li><a href="ootdposts.php">OOTD Posts</a></li>
                <li><a href="settings.php">Settings</a></li>
                <li><a href="aboutus.php">About Us</a></li>
                <li><a href="faqs.php">FAQs</a></li>
            </ul>
        </div>
    </nav>

    <div class="container">
        <main>
            <section class="banner">
                <div class="banner-content">
                    <h1>Welcome to Online Shopping!</h1>
                    <p>Discover the latest trends and exclusive deals.</p>
                </div>
            </section>

            <section class="featured-products">
                <h2>Featured Products</h2>
                <div class="product-card">
                    <img src="item1.jpg" alt="Product 1">
                    <h3>Product Name</h3>
                    <p>$99.99</p>
                    <form action="{{ route('addtocart') }}" method="post">
                        <input type="hidden" name="product_id" value="1">
                        <button type="submit">Add to Cart</button>
                    </form>
                </div>
                <!-- More product cards -->
            </section>
        </main>
    </div>

    <div class="footer-container">
        <footer>
            <p>&copy; 2024 Online Shopping. All rights reserved.</p>
        </footer>
    </div>
</body>
</html>

shoppingcart.blade.php


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Shopping Cart Page</title>
    <link rel="stylesheet" href="StyleNavBar.css">
</head>
<body>
    <nav class="navbar">
        <div class="container">
            <div class="logo">
                <img src="logo_no_name.png" alt="Logo">
            </div>
            <ul class="nav-links">
                <li><a href="{{ route('dashboard') }}">Dashboard</a></li>
                <li><a href="{{ route('home') }}">Home</a></li>
                <li><a href="{{ route('shoppingcart') }}">Shopping Cart</a></li>  
                <li><a href="{{ route('OOTDposts') }}">OOTD Posts</a></li> 
                <li><a href="{{ route('settings') }}">Settings</a></li>
                <li><a href="{{ route('aboutus') }}">About Us</a></li>
                <li><a href="{{ route('FAQs') }}">FAQs</a></li>
            </ul>
        </div>
        </nav>

    <div class="main-container">
        <h1>Shopping Cart</h1>
        <?php if (empty($cart)): ?>
            <p>Your cart is empty.</p>
        <?php else: ?>
            <ul>
                <?php foreach ($cart as $product_id => $quantity): ?>
                    <li>Product ID: <?php echo $product_id; ?> - Quantity: <?php echo $quantity; ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>
</body>
</html>

addtocart.blade.php

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = $_POST['product_id'];

    // Initialize the cart if it doesn't exist
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }

    // Add product to cart
    if (isset($_SESSION['cart'][$product_id])) {
        $_SESSION['cart'][$product_id]++;
    } else {
        $_SESSION['cart'][$product_id] = 1;
    }

    // Redirect to shopping cart page
    header('Location: shoppingcart.php');
    exit;
}
?>

web.php


Route::get('/home',[HomeController::class, 'home'])->name('home');

Route::get('/shoppingcart', [CartController::class, 'showcart'])->name('shoppingcart');
Route::post('/addtocart', [CartController::class, 'addtocart'])->name('addtocart');

CartController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CartController extends Controller
{
    public function addtocart(Request $request)
    {
        $product_id = $request->input('product_id');
        
        $cart = session()->get('cart', []);

        if(isset($cart[$product_id])) {
            $cart[$product_id]++;
        } else {
            $cart[$product_id] = 1;
        }

        session(['cart' => $cart]);

        return redirect()->route('shoppingcart');
    }

    public function showcart()
    {
        $cart = session('cart', []);

        return view('shoppingcart', compact('cart'));
    }
}

Supposedly, when a user clicks the add to cart button on the home page, it redirects to the shopping cart page.

6
  • 2
    It looks like you're not taking advantage of Laravel's routes and controllers properly. Your form action is addtocart.php, which doesn't exist. Your actual route is /add-to-cart, as created in your web.php routes. You should have absolutely no cart logic in your blade files, it should be in the controller.
    – aynber
    Commented May 22 at 18:42
  • 2
    Laravel and other frameworks do not work like traditional PHP sites, there's a lot of functionality that you can take advantage of. I suggest looking into some good tutorials on how Laravel works, such as laracasts.com
    – aynber
    Commented May 22 at 18:42
  • this is hard :(
    – ARA12
    Commented May 22 at 18:51
  • im gonna make some edits in the code
    – ARA12
    Commented May 22 at 18:52
  • 1
    "this is hard" - Funny that you say that about Laravel when it's designed to make working with PHP much easier 😅 That being said, you need to have a pretty solid grasp of PHP Web Development and how Laravel is replacing that logic before you can use Laravel effectively. For example, you can use raw PHP in Laravel's .blade.php files, but there are replacements. <?php if (...) { ?> ... <?php } ?> can be written as @if(...) @endif. <?php foreach(...) { ?> <?php } ?> is @foreach(...) @endforeach, etc. Follow some tutorials, read some documentation, and you'll get the hang of it 🙂
    – Tim Lewis
    Commented May 22 at 21:25

1 Answer 1

0

Your form doesn't have the right action, it should use the route() helper:

<form action="{{ route('addtocart') }}" method="post">

addtocart.blade.php isn't needed because that's covered by the addtocart method in your CartController

And you can get rid of the session start part at the top of the shoppingcart.blade.php, because the framework already starts the session and you pass the $cart to the blade view.

The rest looks okay to me.

Documentation on the route helper

5
  • 1
    fyi, ->name('addtocart') the route name is addtocart
    – brombeer
    Commented May 22 at 19:08
  • i took out the addtocart.blade.php on the views directory and replaced the actions in the home page. However, I made some edits a while ago so I don't know now if its still right. I'll edit the codes on the questions so that u can see the changes. Also, it says page expired when I click the add to cart haha
    – ARA12
    Commented May 22 at 19:25
  • I've edited the codes in the question, hope u can help me again
    – ARA12
    Commented May 22 at 19:29
  • 1
    @brombeer I edited that, but then went back and forth and forgot to edit it again. Thanks for the heads up! Commented May 23 at 7:18
  • @PENDONARAFAITH Add @csrf() on the line right after the form for add to cart opens. Should fix the 419 expired error. Commented May 23 at 7:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.