Updating Database Field with AJAX Laravel





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am trying to update my stock level by subtracting the cart item quantity from the product quantity in the database when a user completes an order using the POST method. Everytime I run the method the success function occurs but the field doesnt update doesnt update.



Could anyone tell me why?



My Controller:



public function index ()
{
$products = Product::all();


return view('products', compact('products'));
}


public function cart()

{
return view('cart');
}

public function addToCart($id)
{
$product = Product::find($id);

if(!$product) {

abort(404);

}

$cart = session()->get('cart');

// if cart is empty then this will be the first product
if(!$cart) {

$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
]
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

// if cart isnt empty then check if this product exist then increment quantity
if(isset($cart[$id])) {

$cart[$id]['quantity']++;

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');

}

// if item doesnt exist in cart then add to cart with quantity = 1
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

public function update(Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]["quantity"] = $request->quantity;

session()->put('cart', $cart);

session()->flash('success', 'Cart updated successfully');
}
}

public function remove(Request $request)
{
if($request->id) {

$cart = session()->get('cart');

if(isset($cart[$request->id])) {

unset($cart[$request->id]);

session()->put('cart', $cart);
}

session()->flash('success', 'Product removed successfully');
}
}

public function stock (Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]['quantity'] = $request->quantity;

$products = Product::all();

$stock = $products->unit_stock;

$quantity = $stock - $cart;

return $quantity;
}
}


My Route:



Route::post('stock', 'ProductController@stock');


My view cart.blade.php:



@extends('layout')



@section('content')

<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th style="width:50%">Product</th>
<th style="width:10%">Price</th>
<th style="width:8%">Quantity</th>
<th style="width:22%" class="text-center">Subtotal</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody>

<?php $total = 0 ?>

@if(session('cart'))
@foreach(session('cart') as $id => $details)

<?php $total += $details['price'] * $details['quantity'] ?>

<tr>
<td data-th="Product">
<div class="row">

<div class="col-sm-9">
<h4 class="nomargin">{{ $details['name'] }}</h4>
</div>
</div>
</td>
<td data-th="Price">${{ $details['price'] }}</td>
<td data-th="Quantity">
<input type="number" value="{{ $details['quantity'] }}" class="form-control quantity" />
</td>
<td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
<td class="actions" data-th="">
<button class="btn btn-info btn-sm update-cart" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
<button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
@endforeach
@endif

</tbody>
<tfoot>
<tr class="visible-xs">
<td class="text-center"><strong>Total {{ $total }}</strong></td>
</tr>
<tr>
<td><a href="{{ url('/products') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
</tr>
</tfoot>

<div class="row">
<div class="btn col-md-12">
<a href="{{ url('/cart') }}" id="order-complete">Test</a>
</div>

</div>
</table>

<script type="text/javascript">

$("#order-complete").click(function (e){
e.preventDefault();

var ele = $(this);

$.ajax({
url: '{{ url('stock') }}',
method: "post",
data: {_token: '{{ csrf_token() }}'},
success: function () {

window.location.reload();
}
});
});
</script>

@endsection









share|improve this question

























  • did you check if the $cart contain the intended data ?

    – Mohammed Yassine CHABLI
    Jan 4 at 17:15






  • 1





    This seems confusing. How could $products->unit_stock work as long as $product returns a collection.

    – Abdur Rahman
    Jan 4 at 17:17








  • 1





    1) You're never saving it in the database. 2) I'm surprised you're not getting an error, since $products is a collection of objects and not a single product.

    – aynber
    Jan 4 at 17:18


















0















I am trying to update my stock level by subtracting the cart item quantity from the product quantity in the database when a user completes an order using the POST method. Everytime I run the method the success function occurs but the field doesnt update doesnt update.



Could anyone tell me why?



My Controller:



public function index ()
{
$products = Product::all();


return view('products', compact('products'));
}


public function cart()

{
return view('cart');
}

public function addToCart($id)
{
$product = Product::find($id);

if(!$product) {

abort(404);

}

$cart = session()->get('cart');

// if cart is empty then this will be the first product
if(!$cart) {

$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
]
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

// if cart isnt empty then check if this product exist then increment quantity
if(isset($cart[$id])) {

$cart[$id]['quantity']++;

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');

}

// if item doesnt exist in cart then add to cart with quantity = 1
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

public function update(Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]["quantity"] = $request->quantity;

session()->put('cart', $cart);

session()->flash('success', 'Cart updated successfully');
}
}

public function remove(Request $request)
{
if($request->id) {

$cart = session()->get('cart');

if(isset($cart[$request->id])) {

unset($cart[$request->id]);

session()->put('cart', $cart);
}

session()->flash('success', 'Product removed successfully');
}
}

public function stock (Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]['quantity'] = $request->quantity;

$products = Product::all();

$stock = $products->unit_stock;

$quantity = $stock - $cart;

return $quantity;
}
}


My Route:



Route::post('stock', 'ProductController@stock');


My view cart.blade.php:



@extends('layout')



@section('content')

<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th style="width:50%">Product</th>
<th style="width:10%">Price</th>
<th style="width:8%">Quantity</th>
<th style="width:22%" class="text-center">Subtotal</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody>

<?php $total = 0 ?>

@if(session('cart'))
@foreach(session('cart') as $id => $details)

<?php $total += $details['price'] * $details['quantity'] ?>

<tr>
<td data-th="Product">
<div class="row">

<div class="col-sm-9">
<h4 class="nomargin">{{ $details['name'] }}</h4>
</div>
</div>
</td>
<td data-th="Price">${{ $details['price'] }}</td>
<td data-th="Quantity">
<input type="number" value="{{ $details['quantity'] }}" class="form-control quantity" />
</td>
<td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
<td class="actions" data-th="">
<button class="btn btn-info btn-sm update-cart" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
<button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
@endforeach
@endif

</tbody>
<tfoot>
<tr class="visible-xs">
<td class="text-center"><strong>Total {{ $total }}</strong></td>
</tr>
<tr>
<td><a href="{{ url('/products') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
</tr>
</tfoot>

<div class="row">
<div class="btn col-md-12">
<a href="{{ url('/cart') }}" id="order-complete">Test</a>
</div>

</div>
</table>

<script type="text/javascript">

$("#order-complete").click(function (e){
e.preventDefault();

var ele = $(this);

$.ajax({
url: '{{ url('stock') }}',
method: "post",
data: {_token: '{{ csrf_token() }}'},
success: function () {

window.location.reload();
}
});
});
</script>

@endsection









share|improve this question

























  • did you check if the $cart contain the intended data ?

    – Mohammed Yassine CHABLI
    Jan 4 at 17:15






  • 1





    This seems confusing. How could $products->unit_stock work as long as $product returns a collection.

    – Abdur Rahman
    Jan 4 at 17:17








  • 1





    1) You're never saving it in the database. 2) I'm surprised you're not getting an error, since $products is a collection of objects and not a single product.

    – aynber
    Jan 4 at 17:18














0












0








0








I am trying to update my stock level by subtracting the cart item quantity from the product quantity in the database when a user completes an order using the POST method. Everytime I run the method the success function occurs but the field doesnt update doesnt update.



Could anyone tell me why?



My Controller:



public function index ()
{
$products = Product::all();


return view('products', compact('products'));
}


public function cart()

{
return view('cart');
}

public function addToCart($id)
{
$product = Product::find($id);

if(!$product) {

abort(404);

}

$cart = session()->get('cart');

// if cart is empty then this will be the first product
if(!$cart) {

$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
]
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

// if cart isnt empty then check if this product exist then increment quantity
if(isset($cart[$id])) {

$cart[$id]['quantity']++;

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');

}

// if item doesnt exist in cart then add to cart with quantity = 1
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

public function update(Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]["quantity"] = $request->quantity;

session()->put('cart', $cart);

session()->flash('success', 'Cart updated successfully');
}
}

public function remove(Request $request)
{
if($request->id) {

$cart = session()->get('cart');

if(isset($cart[$request->id])) {

unset($cart[$request->id]);

session()->put('cart', $cart);
}

session()->flash('success', 'Product removed successfully');
}
}

public function stock (Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]['quantity'] = $request->quantity;

$products = Product::all();

$stock = $products->unit_stock;

$quantity = $stock - $cart;

return $quantity;
}
}


My Route:



Route::post('stock', 'ProductController@stock');


My view cart.blade.php:



@extends('layout')



@section('content')

<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th style="width:50%">Product</th>
<th style="width:10%">Price</th>
<th style="width:8%">Quantity</th>
<th style="width:22%" class="text-center">Subtotal</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody>

<?php $total = 0 ?>

@if(session('cart'))
@foreach(session('cart') as $id => $details)

<?php $total += $details['price'] * $details['quantity'] ?>

<tr>
<td data-th="Product">
<div class="row">

<div class="col-sm-9">
<h4 class="nomargin">{{ $details['name'] }}</h4>
</div>
</div>
</td>
<td data-th="Price">${{ $details['price'] }}</td>
<td data-th="Quantity">
<input type="number" value="{{ $details['quantity'] }}" class="form-control quantity" />
</td>
<td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
<td class="actions" data-th="">
<button class="btn btn-info btn-sm update-cart" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
<button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
@endforeach
@endif

</tbody>
<tfoot>
<tr class="visible-xs">
<td class="text-center"><strong>Total {{ $total }}</strong></td>
</tr>
<tr>
<td><a href="{{ url('/products') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
</tr>
</tfoot>

<div class="row">
<div class="btn col-md-12">
<a href="{{ url('/cart') }}" id="order-complete">Test</a>
</div>

</div>
</table>

<script type="text/javascript">

$("#order-complete").click(function (e){
e.preventDefault();

var ele = $(this);

$.ajax({
url: '{{ url('stock') }}',
method: "post",
data: {_token: '{{ csrf_token() }}'},
success: function () {

window.location.reload();
}
});
});
</script>

@endsection









share|improve this question
















I am trying to update my stock level by subtracting the cart item quantity from the product quantity in the database when a user completes an order using the POST method. Everytime I run the method the success function occurs but the field doesnt update doesnt update.



Could anyone tell me why?



My Controller:



public function index ()
{
$products = Product::all();


return view('products', compact('products'));
}


public function cart()

{
return view('cart');
}

public function addToCart($id)
{
$product = Product::find($id);

if(!$product) {

abort(404);

}

$cart = session()->get('cart');

// if cart is empty then this will be the first product
if(!$cart) {

$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
]
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

// if cart isnt empty then check if this product exist then increment quantity
if(isset($cart[$id])) {

$cart[$id]['quantity']++;

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');

}

// if item doesnt exist in cart then add to cart with quantity = 1
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->unit_price
];

session()->put('cart', $cart);

return redirect()->back()->with('success', 'Product added to cart successfully!');
}

public function update(Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]["quantity"] = $request->quantity;

session()->put('cart', $cart);

session()->flash('success', 'Cart updated successfully');
}
}

public function remove(Request $request)
{
if($request->id) {

$cart = session()->get('cart');

if(isset($cart[$request->id])) {

unset($cart[$request->id]);

session()->put('cart', $cart);
}

session()->flash('success', 'Product removed successfully');
}
}

public function stock (Request $request)
{
if($request->id and $request->quantity)
{
$cart = session()->get('cart');

$cart[$request->id]['quantity'] = $request->quantity;

$products = Product::all();

$stock = $products->unit_stock;

$quantity = $stock - $cart;

return $quantity;
}
}


My Route:



Route::post('stock', 'ProductController@stock');


My view cart.blade.php:



@extends('layout')



@section('content')

<table id="cart" class="table table-hover table-condensed">
<thead>
<tr>
<th style="width:50%">Product</th>
<th style="width:10%">Price</th>
<th style="width:8%">Quantity</th>
<th style="width:22%" class="text-center">Subtotal</th>
<th style="width:10%"></th>
</tr>
</thead>
<tbody>

<?php $total = 0 ?>

@if(session('cart'))
@foreach(session('cart') as $id => $details)

<?php $total += $details['price'] * $details['quantity'] ?>

<tr>
<td data-th="Product">
<div class="row">

<div class="col-sm-9">
<h4 class="nomargin">{{ $details['name'] }}</h4>
</div>
</div>
</td>
<td data-th="Price">${{ $details['price'] }}</td>
<td data-th="Quantity">
<input type="number" value="{{ $details['quantity'] }}" class="form-control quantity" />
</td>
<td data-th="Subtotal" class="text-center">${{ $details['price'] * $details['quantity'] }}</td>
<td class="actions" data-th="">
<button class="btn btn-info btn-sm update-cart" data-id="{{ $id }}"><i class="fa fa-refresh"></i></button>
<button class="btn btn-danger btn-sm remove-from-cart" data-id="{{ $id }}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
@endforeach
@endif

</tbody>
<tfoot>
<tr class="visible-xs">
<td class="text-center"><strong>Total {{ $total }}</strong></td>
</tr>
<tr>
<td><a href="{{ url('/products') }}" class="btn btn-warning"><i class="fa fa-angle-left"></i> Continue Shopping</a></td>
<td colspan="2" class="hidden-xs"></td>
<td class="hidden-xs text-center"><strong>Total ${{ $total }}</strong></td>
</tr>
</tfoot>

<div class="row">
<div class="btn col-md-12">
<a href="{{ url('/cart') }}" id="order-complete">Test</a>
</div>

</div>
</table>

<script type="text/javascript">

$("#order-complete").click(function (e){
e.preventDefault();

var ele = $(this);

$.ajax({
url: '{{ url('stock') }}',
method: "post",
data: {_token: '{{ csrf_token() }}'},
success: function () {

window.location.reload();
}
});
});
</script>

@endsection






php mysql database laravel laravel-5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 18:13







Jeff

















asked Jan 4 at 17:11









JeffJeff

84




84













  • did you check if the $cart contain the intended data ?

    – Mohammed Yassine CHABLI
    Jan 4 at 17:15






  • 1





    This seems confusing. How could $products->unit_stock work as long as $product returns a collection.

    – Abdur Rahman
    Jan 4 at 17:17








  • 1





    1) You're never saving it in the database. 2) I'm surprised you're not getting an error, since $products is a collection of objects and not a single product.

    – aynber
    Jan 4 at 17:18



















  • did you check if the $cart contain the intended data ?

    – Mohammed Yassine CHABLI
    Jan 4 at 17:15






  • 1





    This seems confusing. How could $products->unit_stock work as long as $product returns a collection.

    – Abdur Rahman
    Jan 4 at 17:17








  • 1





    1) You're never saving it in the database. 2) I'm surprised you're not getting an error, since $products is a collection of objects and not a single product.

    – aynber
    Jan 4 at 17:18

















did you check if the $cart contain the intended data ?

– Mohammed Yassine CHABLI
Jan 4 at 17:15





did you check if the $cart contain the intended data ?

– Mohammed Yassine CHABLI
Jan 4 at 17:15




1




1





This seems confusing. How could $products->unit_stock work as long as $product returns a collection.

– Abdur Rahman
Jan 4 at 17:17







This seems confusing. How could $products->unit_stock work as long as $product returns a collection.

– Abdur Rahman
Jan 4 at 17:17






1




1





1) You're never saving it in the database. 2) I'm surprised you're not getting an error, since $products is a collection of objects and not a single product.

– aynber
Jan 4 at 17:18





1) You're never saving it in the database. 2) I'm surprised you're not getting an error, since $products is a collection of objects and not a single product.

– aynber
Jan 4 at 17:18












2 Answers
2






active

oldest

votes


















0














I can see a couple of potential issues that might be causing this. Firstly, it looks like you're trying to set stock against all of the products in your database in one go by loading a collection containing them all, rather than looping/loading the ones contained in the order ($request). You do this here;



$products = Product::all();


Then you try to change the stock for all products in the collection here;



$stock = $products->unit_stock;

$quantity = $stock - $cart;


I imagine you should have a collection of products in your $cart variable that you should loop over and load to manipulate. Some pseudo code to illustrate my point;



foreach($product in $cart){
$loadedProduct = Product::find($product);
$loadedProduct->stock = $loadedProduct->stock - $product["quantity"];
$loadedProduct->save();
}


You also aren't saving any products in the code you provided. There's an example of this in the pseudo code above.






share|improve this answer


























  • Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

    – Jeff
    Jan 4 at 17:36











  • Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

    – Lewis
    Jan 4 at 17:48











  • What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

    – Jeff
    Jan 4 at 17:55













  • It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

    – Lewis
    Jan 4 at 18:10













  • Great thanks! I have updated my question so you see my full controller

    – Jeff
    Jan 4 at 18:14



















0














I can spot a few mistakes from your code.




  1. Lets focus on the function that the ajax request calls.


This line here tells me that there is a data id and quantity being sent.



if($request->id and $request->quantity)


From the look of your Route, it is in the body. But in the ajax function, you're didn't include any data except the csrf token. Try adding id and quantity data. This is just an assumption of the value.



       data: {_token: '{{ csrf_token() }}', id: 6, quantity: 2},


Secondly, this function returns a collections of product.



$products = Product::all();


So if you would like to modify a product you must access its index. e.g.



$products[0]->unit_stock = 3; 
$products[0]->save();


Or what Lewis has stated, you can use a foreach loop to iterate every object in the collection






share|improve this answer
























  • Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

    – Adis
    Jan 4 at 19:20












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043322%2fupdating-database-field-with-ajax-laravel%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I can see a couple of potential issues that might be causing this. Firstly, it looks like you're trying to set stock against all of the products in your database in one go by loading a collection containing them all, rather than looping/loading the ones contained in the order ($request). You do this here;



$products = Product::all();


Then you try to change the stock for all products in the collection here;



$stock = $products->unit_stock;

$quantity = $stock - $cart;


I imagine you should have a collection of products in your $cart variable that you should loop over and load to manipulate. Some pseudo code to illustrate my point;



foreach($product in $cart){
$loadedProduct = Product::find($product);
$loadedProduct->stock = $loadedProduct->stock - $product["quantity"];
$loadedProduct->save();
}


You also aren't saving any products in the code you provided. There's an example of this in the pseudo code above.






share|improve this answer


























  • Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

    – Jeff
    Jan 4 at 17:36











  • Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

    – Lewis
    Jan 4 at 17:48











  • What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

    – Jeff
    Jan 4 at 17:55













  • It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

    – Lewis
    Jan 4 at 18:10













  • Great thanks! I have updated my question so you see my full controller

    – Jeff
    Jan 4 at 18:14
















0














I can see a couple of potential issues that might be causing this. Firstly, it looks like you're trying to set stock against all of the products in your database in one go by loading a collection containing them all, rather than looping/loading the ones contained in the order ($request). You do this here;



$products = Product::all();


Then you try to change the stock for all products in the collection here;



$stock = $products->unit_stock;

$quantity = $stock - $cart;


I imagine you should have a collection of products in your $cart variable that you should loop over and load to manipulate. Some pseudo code to illustrate my point;



foreach($product in $cart){
$loadedProduct = Product::find($product);
$loadedProduct->stock = $loadedProduct->stock - $product["quantity"];
$loadedProduct->save();
}


You also aren't saving any products in the code you provided. There's an example of this in the pseudo code above.






share|improve this answer


























  • Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

    – Jeff
    Jan 4 at 17:36











  • Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

    – Lewis
    Jan 4 at 17:48











  • What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

    – Jeff
    Jan 4 at 17:55













  • It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

    – Lewis
    Jan 4 at 18:10













  • Great thanks! I have updated my question so you see my full controller

    – Jeff
    Jan 4 at 18:14














0












0








0







I can see a couple of potential issues that might be causing this. Firstly, it looks like you're trying to set stock against all of the products in your database in one go by loading a collection containing them all, rather than looping/loading the ones contained in the order ($request). You do this here;



$products = Product::all();


Then you try to change the stock for all products in the collection here;



$stock = $products->unit_stock;

$quantity = $stock - $cart;


I imagine you should have a collection of products in your $cart variable that you should loop over and load to manipulate. Some pseudo code to illustrate my point;



foreach($product in $cart){
$loadedProduct = Product::find($product);
$loadedProduct->stock = $loadedProduct->stock - $product["quantity"];
$loadedProduct->save();
}


You also aren't saving any products in the code you provided. There's an example of this in the pseudo code above.






share|improve this answer















I can see a couple of potential issues that might be causing this. Firstly, it looks like you're trying to set stock against all of the products in your database in one go by loading a collection containing them all, rather than looping/loading the ones contained in the order ($request). You do this here;



$products = Product::all();


Then you try to change the stock for all products in the collection here;



$stock = $products->unit_stock;

$quantity = $stock - $cart;


I imagine you should have a collection of products in your $cart variable that you should loop over and load to manipulate. Some pseudo code to illustrate my point;



foreach($product in $cart){
$loadedProduct = Product::find($product);
$loadedProduct->stock = $loadedProduct->stock - $product["quantity"];
$loadedProduct->save();
}


You also aren't saving any products in the code you provided. There's an example of this in the pseudo code above.







share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 4 at 18:15

























answered Jan 4 at 17:20









LewisLewis

1,955821




1,955821













  • Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

    – Jeff
    Jan 4 at 17:36











  • Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

    – Lewis
    Jan 4 at 17:48











  • What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

    – Jeff
    Jan 4 at 17:55













  • It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

    – Lewis
    Jan 4 at 18:10













  • Great thanks! I have updated my question so you see my full controller

    – Jeff
    Jan 4 at 18:14



















  • Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

    – Jeff
    Jan 4 at 17:36











  • Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

    – Lewis
    Jan 4 at 17:48











  • What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

    – Jeff
    Jan 4 at 17:55













  • It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

    – Lewis
    Jan 4 at 18:10













  • Great thanks! I have updated my question so you see my full controller

    – Jeff
    Jan 4 at 18:14

















Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

– Jeff
Jan 4 at 17:36





Hi Lewis, thanks for this i understand it better! just a couple things, in the foreach statement, "in" isnt recognised as syntax, would "as" be suitable? When i changed it to this the page worked, however when I get a 500 error now when the Ajax method starts

– Jeff
Jan 4 at 17:36













Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

– Lewis
Jan 4 at 17:48





Hey. Yes, "as" is correct here, sorry had just been writing similar code in JS :) The code above is pseudo only. Have you changed it to match your own?

– Lewis
Jan 4 at 17:48













What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

– Jeff
Jan 4 at 17:55







What would I need to change? I have changed just "stock" to "unit_stock" as that is the field in the database, would that be everything?

– Jeff
Jan 4 at 17:55















It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

– Lewis
Jan 4 at 18:10







It's hard to say for sure, as I can't see your cart object. I am only guessing from what you posted but it looks like your cart object is just an array of products with the keys set as product ids? If that's the case, in the foreach I posted, drop the products key. Inside, use just Product::find($product) to load the product. I'm on mobile right now so will help later if I can and if these changes don't work.

– Lewis
Jan 4 at 18:10















Great thanks! I have updated my question so you see my full controller

– Jeff
Jan 4 at 18:14





Great thanks! I have updated my question so you see my full controller

– Jeff
Jan 4 at 18:14













0














I can spot a few mistakes from your code.




  1. Lets focus on the function that the ajax request calls.


This line here tells me that there is a data id and quantity being sent.



if($request->id and $request->quantity)


From the look of your Route, it is in the body. But in the ajax function, you're didn't include any data except the csrf token. Try adding id and quantity data. This is just an assumption of the value.



       data: {_token: '{{ csrf_token() }}', id: 6, quantity: 2},


Secondly, this function returns a collections of product.



$products = Product::all();


So if you would like to modify a product you must access its index. e.g.



$products[0]->unit_stock = 3; 
$products[0]->save();


Or what Lewis has stated, you can use a foreach loop to iterate every object in the collection






share|improve this answer
























  • Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

    – Adis
    Jan 4 at 19:20
















0














I can spot a few mistakes from your code.




  1. Lets focus on the function that the ajax request calls.


This line here tells me that there is a data id and quantity being sent.



if($request->id and $request->quantity)


From the look of your Route, it is in the body. But in the ajax function, you're didn't include any data except the csrf token. Try adding id and quantity data. This is just an assumption of the value.



       data: {_token: '{{ csrf_token() }}', id: 6, quantity: 2},


Secondly, this function returns a collections of product.



$products = Product::all();


So if you would like to modify a product you must access its index. e.g.



$products[0]->unit_stock = 3; 
$products[0]->save();


Or what Lewis has stated, you can use a foreach loop to iterate every object in the collection






share|improve this answer
























  • Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

    – Adis
    Jan 4 at 19:20














0












0








0







I can spot a few mistakes from your code.




  1. Lets focus on the function that the ajax request calls.


This line here tells me that there is a data id and quantity being sent.



if($request->id and $request->quantity)


From the look of your Route, it is in the body. But in the ajax function, you're didn't include any data except the csrf token. Try adding id and quantity data. This is just an assumption of the value.



       data: {_token: '{{ csrf_token() }}', id: 6, quantity: 2},


Secondly, this function returns a collections of product.



$products = Product::all();


So if you would like to modify a product you must access its index. e.g.



$products[0]->unit_stock = 3; 
$products[0]->save();


Or what Lewis has stated, you can use a foreach loop to iterate every object in the collection






share|improve this answer













I can spot a few mistakes from your code.




  1. Lets focus on the function that the ajax request calls.


This line here tells me that there is a data id and quantity being sent.



if($request->id and $request->quantity)


From the look of your Route, it is in the body. But in the ajax function, you're didn't include any data except the csrf token. Try adding id and quantity data. This is just an assumption of the value.



       data: {_token: '{{ csrf_token() }}', id: 6, quantity: 2},


Secondly, this function returns a collections of product.



$products = Product::all();


So if you would like to modify a product you must access its index. e.g.



$products[0]->unit_stock = 3; 
$products[0]->save();


Or what Lewis has stated, you can use a foreach loop to iterate every object in the collection







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 4 at 19:17









AdisAdis

413418




413418













  • Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

    – Adis
    Jan 4 at 19:20



















  • Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

    – Adis
    Jan 4 at 19:20

















Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

– Adis
Jan 4 at 19:20





Honestly, I think there are flaws in @Jeff 's code logic. Correct me if I'm wrong, but you're trying to update products' stock that has been purchased/ added to cart. Therefore you need to save the ids of each product added in that cart, that you haven't done. Once you've the id of each product, you can use that call find function and update the product's quantity.

– Adis
Jan 4 at 19:20


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043322%2fupdating-database-field-with-ajax-laravel%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas