If I select "black" I know from the db that the size "14-16" is the only one that has stock, but yet
shows all three sizes.
DB:

I've posted about this before but thought it would be better posting again as I've made a couple of changes to certain area's, plus I didn't want to go through everything again and everyone get mixed up. So here goes.....
I've built a custom e-commerce site that sells clothing, each clothing item has colour, size and stock in the product_options table, like so:

Then the related product it'self is:

Now this works but it shows available colours even though stock is set to zero/0 which isn't right you need to select a colour once then some JS looks up the product_options table to send back this info as a JSON response.
Like so:
$(function(){
$('.colors').on('change', function(e){
var cat_id = e.target.value;
var current = $(this).data("index");
var select = $("select[data-index='"+current+"'][class='sizes']");
$.get('/related-sizes?info=' + cat_id, function(data){
select.empty();
$.each(data, function(index, subcatObj){
select.append('<option value="'+subcatObj.size+'">'+subcatObj.size+'</option>');
});
});
});
var a = new Array();
$(".colors").children("option").each(function(x){
test = false;
b = a[x] = $(this).val();
for (i=0;i<a.length-1;i++){
// if (b ==a[i]) test =true;
if (b ==a[i] && b != '') test =true;
}
if (test) $(this).remove();
});
});
Which gets sent to this method:
public function selectedColour()
{
$info = explode('-', Input::get('info'));
$cat = Options::where('product_id', $info[0])
->where('colour', $info[1])
->orderBy('size', 'asc')
->get(['id', 'size', 'colour', 'stock']);
return Response::json($cat, 200);
}
This is the underlining HTML
<div class="product-details">
@if($item->availableColours() && $item->availableStock())
Colour
<select name="colour" class="colors" data-index="{{ $item->id }}">
<option value="" selected="selected">Please Select</option>
@foreach($item->options as $option)
<option value="{{ $option->product_id }}-{{ $option->colour }}">{{ $option->colour }}</option>
@endforeach
</select>
@endif
<br />
@if($item->availableSizes())
Size:
<select name="size" class="sizes" data-index="{{ $item->id }}">
<option value=""></option>
</select>
@endif
</div>
The Product Model:
public function options()
{
return $this->hasMany('Options','product_id', 'id');
}
public function availableColours()
{
return $this->options()->select('colour')->distinct()->where('stock', '>', 0)->lists('colour');
}
public function availableSizes()
{
return $this->options()->select('size')->distinct()->where('stock', '>', 0)->lists('size');
}
public function availableStock()
{
return $this->options()->select('stock')->distinct()->where('stock', '>', 0)->lists('stock');
}
So I need some way to check it has stock of at least 1 to be returned and only show each colour in the first select menu once. Can someone please help me with this?
Thanks in advance :)
Please or to participate in this conversation.