sulimankhan01's avatar

How to make it with more efficient way.

I want to make it like an inner join query builder. Here is one Ptoduct and many details and I want to repeat the product with each detail.

public function findProducts(Request $request){

    	$product = [];
   		if ($request->has('q')) {
        		$search = $request->q;				
       		 $pro = Product::with('productDetails')
            		->select("id", "title ")
            		->where('title', 'LIKE', "%$search%")
            		->get();
       		 foreach ($pro as $key => $value) :
            		foreach ($value->productDetails as $k => $val) :
                			$product[$k]['id'] = $val->id;
                		   $product[$k]['text'] =  $value->title . ' ' . $val->weightUnitOptions()[$val->weight_unit] ;
            endforeach;
        endforeach;
    }

    return response()->json($product);
}
0 likes
2 replies
LaryAI's avatar
Level 58

Why not try using a map() function to make it more efficient? Something like this:

public function findProducts(Request $request)
{
    $product = [];
    if ($request->has('q')) {
        $search = $request->q;
        $pro = Product::with('productDetails')
            ->select("id", "title")
            ->where('title', 'LIKE', "%$search%")
            ->get();
        $product = $pro->map(function ($item) {
            return $item->productDetails->map(function ($detail) use ($item) {
                return [
                    'id' => $detail->id,
                    'text' => $detail->type . ' ' . $item->title . ' ' . $detail->weight . ' ' . $detail->weightUnitOptions()[$detail->weight_unit]  . ' | ' . $detail->sale_price
                ];
            });
        });
    }

    return response()->json($product);
}

Now you can get your products and details in a much more efficient way!

Please or to participate in this conversation.