Reputation: 33
What's wrong with my code? Is it the javascript or the controller?
here is my Route:
Route::get('/cartupdate', 'FrontEndController@cartupdate')->name('update.cart');
Route::post('/cartupdate', 'FrontEndController@cartupdate')->name('cart.update');
Controller code is here:
public function cartupdate(Request $request)
{
if ($request->isMethod('post')){
if (empty(Session::get('uniqueid'))){
$cart = new Cart;
$cart->fill($request->all());
Session::put('uniqueid', $request->uniqueid);
$cart->save();
}else{
$cart = Cart::where('uniqueid',$request->uniqueid)
->where('product',$request->product)->first();
//$carts = Cart::where('uniqueid',$request->uniqueid)
//->where('product',$request->product)->count();
if (count($cart) > 0 ){
$data = $request->all();
$cart->update($data);
}else{
$cart = new Cart;
$cart->fill($request->all());
$cart->save();
}
}
return response()->json(['response' => 'Successfully Added to Cart.','product' => $request->product]);
}
$getcart = Cart::where('uniqueid',Session::get('uniqueid'))->get();
return response()->json(['response' => $getcart]);
}
jQuery code is here:
$(".to-cart").click(function(){
var formData = $(this).parents('form:first').serializeArray();
$.ajax({
type: "POST",
url: '{{route("cart.update")}}',
data:formData,
success: function (data) {
getCart();
$.notify(data.response, "success");
},
error: function (data) {
console.log('Error:', data);
}
});
});
View code is here:
<form>
<p>
{{csrf_field()}}
@if(Session::has('uniqueid'))
<input type="hidden" name="uniqueid" value="{{Session::get('uniqueid')}}">
@else
<input type="hidden" name="uniqueid" value="{{str_random(7)}}">
@endif
<input type="hidden" name="title" value="{{$product->title}}">
<input type="hidden" name="product" value="{{$product->id}}">
<input type="hidden" id="cost" name="cost" value="{{$product->price}}">
<input type="hidden" id="quantity" name="quantity" value="1">
@if($product->stock != 0 || $product->stock === null )
<button type="button" class="button style-10 to-cart">Add to cart</button>
@else
<button type="button" class="button style-10 to-cart" disabled>Out Of Stock</button>
@endif
{{--<button type="button" class="button style-10 hidden-sm to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</button>--}}
</p>
</form>
Upvotes: 1
Views: 3232
Reputation: 33
the problem was in $cart variable returned null i just changed from
if (count($cart) > 0 ){
$data = $request->all();
$cart->update($data);
}
to this:
if ($cart){
$data = $request->all();
$cart->update($data);
}
and problem solve Thanks to all :)
Upvotes: 0
Reputation: 5081
Based on your comment, looks like you are using count()
on a non-array element, that's prohibited. You should modify your check:
From:
if (count($cart) > 0 ){
To:
if (is_array($cart) && count($cart) > 0 ){
Tip: Verify first that $cart
is an array before checking its length.
Upvotes: 1