Falady
Falady

Reputation: 124

Too few arguments to pass to a function in Laravel

I am new to Laravel and trying to create an add to cart function. But I'm getting this error when i click on the "add to cart" icon/button which i have set.

Too few arguments to function App\Http\Controllers\ProductController::getAddToCart(), 1 passed and exactly 2 expected

I have seen many similar questions but most of the answers look complicated and does not seem to similar to my issues. Again, I am new in Laravel and would need the simplest form of explanation. Below are my ProductController and route codes

ProductController:

<?php
namespace App\Http\Controllers;

use App\Cart;
use App\Product;
use Illuminate\Http\Request;

use App\Http\Requests;
use Session;

class ProductController extends Controller
{
    public function getProducts()
    {
        $products = Product::all();
        return view('shop', ['products' => $products]);
    }

    public function getAddToCart(Request $request, $id)
    {
        $product = Product::find($id);
        $oldCart = Session::has('cart') ? Session::get('cart') : null;
        $cart = new Cart($oldCart);
        $cart->add($product, $product->id);

        $request->session()->put('cart', $cart);
        dd($request->session()->get('cart'));
        return redirect()->route('shop');
    }
}

route for add to cart function:

Route::get('/add-to-cart', ['uses' => 'ProductController@getAddToCart', 'as' => 'product.addToCart']);

P/S: I am using Laravel 6

Upvotes: 1

Views: 1650

Answers (1)

Pravin Prajapati
Pravin Prajapati

Reputation: 50

You need to change your route as below

Route::get('/add-to-cart/{id}', ['uses' => 'ProductController@getAddToCart', 'as' => 'product.addToCart']);

Upvotes: 2

Related Questions