Reputation: 147
Question :
I have a table called product
with some bunch of columns. One of which is name
. The problem is :
Sample entries:
The problem
When i do a query for https://example.com/public/api/products?search=name%3Apowder
I get 0 results .
Expectation is to return
Salt Powder & Chilli powdeR since the term "powder" is common in both.
Now when i do a query for https://example.com/public/api/products?search=name%3Asalt+powder
, i get Salt powder
as the result.
Here's my controller
& what i have been trying to implement in the index :
public function index(Request $request)
{
if (Query::has('search')) { ------>>> I know that something is terribly wrong here.
$queryString = Query::get('search');
$products = Products::where('name', 'LIKE', "%$queryString%")->orderBy('name')->paginate(5);
}
try{
$this->productRepository->pushCriteria(new RequestCriteria($request));
$this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
$this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
if($request->get('trending',null) == 'week'){
$this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
}
else{
$this->productRepository->pushCriteria(new NearCriteria($request));
}
$products = $this->productRepository->all();
} catch (RepositoryException $e) {
return $this->sendError($e->getMessage());
}
return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
}
My productRepository.php
:
<?php
namespace App\Repositories;
use App\Models\Product;
use InfyOm\Generator\Common\BaseRepository;
use Prettus\Repository\Contracts\CacheableInterface;
use Prettus\Repository\Traits\CacheableRepository;
class ProductRepository extends BaseRepository implements CacheableInterface
{
use CacheableRepository;
/**
* @var array
*/
protected $fieldSearchable = [
'name',
'seokeywords',
'price',
'discount_price',
'description',
'capacity',
'package_items_count',
'unit',
'itemsAvailable',
'featured',
'store_id',
'category_id',
'brand_id'
];
/**
* Configure the Model
**/
public function model()
{
return Product::class;
}
/**
* get my products
**/
public function myProducts()
{
return Product::join("user_stores", "user_stores.store_id", "=", "products.store_id")
->where('user_stores.user_id', auth()->id())->get();
}
}
Can someone please help to understand what or which statement should i modify ? I've tried changes but most attempts ended in errors. Any help is much appreciated. I can share any files that you guys may be interested to peak into
Upvotes: 0
Views: 177
Reputation: 2062
you can use $request->query
to get the query string, and because you have "name:" included in it, you need to extract the search term:
if ($queryString = $request->query('search')) {
[$column, $term] = explode(':', $queryString);
$products = Products::where('name', 'LIKE', "%{$term}%")
->orderBy('name')
->paginate(5);
}
note: aren't you missing an else clause? you seem to be overriding the $products variable.
Upvotes: 1