Search code examples
laraveleloquentmany-to-many

dynamic product using laravel


I'm new in web developing. I'm trying to add dynamic product to my eCommerce website. This is my database structure: database design

options table for attributes like: size, color.

choices table for different options like: red, blue, large, small.

My question is how I can reach Instance by having choices (instances and choices have many to many relationship). For example when selecting blue and small by user I want to get the price through ajax, How I can reach Instance to return price with these choices?In other words, consider Instance and Choice models have many to many relationship. If I have one choice, I can easily reach its instances through many to many relationship. But how can I reach instances (in my case only one instance) when I have two or more choices? Now I'm using following code, but I think there should be an easier way to do this:

$choices = Choice::findOrFail($request->choices);
$collection = collect();
foreach($choices as $choice){
    $ids = $choice->instances->where('product_id',$request->product_id)->pluck('id');
    $collection = $collection->merge($ids);
}
$array = $collection->toArray();
$values = array_count_values($array);
arsort($values);
$instance_id = array_slice(array_keys($values), 0, 1, true);
$instance = Instance::where('id',$instance_id[0])->first();
return $instance->price_sell;

Solution

  • You can use pluck() and collapse():

    $choices = Choice::with('instances')->findOrFail($request->choices);
    $instances = $choices->pluck('instances')->collapse();
    $ids = $instances->where('product_id', $request->product_id)->pluck('id');
    $values = array_count_values($ids->all());
    arsort($values);
    $instance = $instances->find(array_keys($values)[0]);
    return $instance->price_sell;
    

    with('instances') eager loads the instances to reduce the number of queries.