'Inertia post request
Kind of new to Inertia, so this may be a stupid question.
I'm trying to install this package https://github.com/darryldecode/laravelshoppingcart on my Laravel 8/Inertia eCommerce SPA.
Now, in order to add a product to the cart, or so I understand, I need to send a post request with the product data to this function within a controller:
public function addToCart(Request $request)
{
$product = $this->findProductById($request->input('productId'));
$options = $request->except('_token', 'productId', 'price', 'qty');
\Cart::add(uniqid(), $product->name, $request->input('price'), $request->input('qty'), $options);
return redirect()->back()->with('message', 'Item added to cart successfully.');
}
The problem is, I'm not entirely sure how to do that. As I need to do this with a button click, forms don't seem like the right way to go.
The only other way is to do this (that I know of) via a method, but onclick activated method on a button always returns the same error: this $methodname is not a function.
Any input into any of this would be appreciated.
EDIT: I managed to go around the problem by using inertia link like so
<inertia-link
:href="route('product.add.cart')"
method="post"
:data="{
productId: product.id,
price: product.price,
quantity: 1,
name: product.name,
}"
classes="px-3 py-2 mr-2 rounded text-white text-sm font-bold whitespace-no-wrap bg-blue-600 hover:bg-blue-800"
as="button"
>AddtoCart</inertia-link>
and the problem now is the validation here
protected function validate($item)
{
$rules = array(
'productId' => 'required',
'price' => 'required|numeric',
'quantity' => 'required|numeric|min:0.1',
'name' => 'required',
);
$validator = CartItemValidator::make($item, $rules);
if ($validator->fails()) {
throw new InvalidItemException($validator->messages()->first());
}
return $item;
}
What I find quite interesting is that if I post the array as it was shown above, because of the validator rules, an exception will be thrown. If I set the first parameter's name to id however, an exception will be thrown stating that the first parameter was delivered a null when expecting an integer (dd shows it as integer).
The most puzzling part however is that if i comment out the if exception on the validator, and keep the first parameter named productId, it works and the product is added to the cart.
I know editing vendor files is bad practice though, and I am quite curious what could possibly be causing this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
