dimanche 30 août 2020

Laravel | Unable to get array of strings searched from the database

What is the ultimate use-case ?

My mobile App is going to send a query for https://example.com/public/api/classifiedsearch?search=name%3Aorange+apples+grapes+onions

& I'd expect the results to include data from the products table with name containing the term in the search strings above. The problem that I'm facing is that, i don't get any results matched at all. I have confirmed by printing that $terms (referred below) is indeed able to capture the values from search as an array & the for loop is working the number of times equalent to the number of words in search string. But no results returned. Any hint/suggestions to why isn't it mapping ????

Here's what i have done in my APIcontroller for classifiedsearch

public function index(Request $request)
{
    try{
       $queryString = $request->input('search',null);
         $terms = explode(" ",$queryString);
    
    // print_r($terms);
              
      if ( !empty( $request->query('search')))
      {
                   
        $products = Product::whereHas('store', function ($query) use ($terms) 
               {
                    foreach ($terms as $term) 
                    {
                     //    print_r("CHECKING FOR $term");
                    $query->where('name', 'like', '%' . $term . '%');
                    
                    }
               })->get();
          
      }
            
      else 
      {       
           $products = $this->productRepository->all(); 
      }
           
    } catch (RepositoryException $e) {
        return $this->sendError($e->getMessage());
    }

    return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
}

Output :

{"success":true,"data":[],"message":"Products retrieved successfully"}

Can someone please help ??



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2YPoHod
via IFTTT

Aucun commentaire:

Enregistrer un commentaire