Anowar Hosen
Anowar Hosen

Reputation: 187

Laravel search query doesn't get results in all cases even though it should

public function find(Request $request)
{
   $validatedData = $request->validate([
     'search' => 'required|max:255',
   ]);
   $item = $request->search;

   $data = DB::table('products')
      ->join('categories','products.category_id','categories.id')
      ->join('subcategories','products.sub_category_id','subcategories.id')
      ->join('sub_of_subcategories','products.sos_category_id','sub_of_subcategories.id')
      ->select('products.*','categories.slug','categories.category_name','subcategories.sub_category_name','sub_of_subcategories.sub_of_sub_category_name')
      ->where('products.product_name','LIKE',"%{$item}%")
      ->orWhere('products.product_code',$item)
      ->orWhere('categories.category_name','LIKE',"%{$item}%")
      ->orWhere('subcategories.sub_category_name','LIKE',"%{$item}%")
      ->orWhere('sub_of_subcategories.sub_of_sub_category_name','LIKE',"%{$item}%")
      ->orWhere('products.product_description','LIKE',"%{$item}%")
      ->paginate(40);

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

When I search by product name or product code or product description, it's showing me the result. but, if I search by category name or sub category name then it's showing me a null array. How can i fix this?

Upvotes: 0

Views: 539

Answers (1)

Shekh Saifuddin
Shekh Saifuddin

Reputation: 518

Your joining query is wrong you have to put = sign in the join function like this

->join('categories', 'products.category_id', '=', 'categories.id')
->join('subcategories', 'products.sub_category_id', '=', 'subcategories.id')
->join('sub_of_subcategories', 'products.sos_category_id', '=', 'sub_of_subcategories.id')

hope it will work

happy coding..

laravel join defination

Upvotes: 1

Related Questions