I am trying to create a search feature for my back-end in Laravel 4 , where I can search for users by ( firstname , lastname , email). I have this function so far but it's not really working :
public function searchUser()
{
$search = Input::get('search');
$searchTerms = explode(' ', $search);
foreach($searchTerms as $term)
{
$query = User::Where('firstname', 'LIKE', '%'. $term .'%');
}
$results = $query->get();
}
How do I get the others like lastname, email in there?
You can do this:
<?php
public function searchUser()
{
$search = Input::get('search');
$searchTerms = explode(' ', $search);
$query = User::query();
$fields = array('first_name', 'last_name', 'email');
foreach ($searchTerms as $term)
{
foreach ($fields as $field)
{
$query->orWhere($field, 'LIKE', '%'. $term .'%');
}
}
$results = $query->get();
}
This way it will do a LIKE query of all search terms in all fields.
You also can paginate it by doing:
$result = $query->paginate(10);
Related
Code(Controller):
public function index(Request $request) {
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));
}
$queryString = $request->query;
if ($queryString = $request->query('search')) {
// [$column, $term] = explode(':', $queryString);
$terms = explode(" ", request('q'));
$products = Product::query()->whereHas('store', function ($query) use ($terms) {
foreach ($terms as $term) {
// Loop over the terms and do a search for each.
$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');
}
I'm getting the complete set of data within the product table as of now. My intension is to be able to filter the results with matching keywords as in $terms . Can someone please help figure out what's missing in filtering above ?
Didn't get much help around & solved this myself. To the ones who may need this in future:
$condition = '';
$terms = explode(" ",$queryString);
foreach($terms as $text)
{
$condition .= "name LIKE '%".($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$sql_query = "SELECT * FROM products WHERE " . $condition;
$result = DB::select($sql_query);
condition is going to gather all the conditions to be searched.
terms is going to collect all searches from the URL text is the
invidual items from the array.
products is the name of the table.
use DB; should be initialized if you're in a different namespace.
I am not sure how to say this, but you will get the idea from the below code. Laravel framework is used.
My code is as shown below:
$keywords = ProductKeyword::orderBy('name', 'asc')->pluck('name')->toArray();
if (!empty($keywords)) {
$str = '';
foreach ($keywords as $key => $keyword) {
if ($key == 0) {
$str .= "Where('description', 'like', '%' . $keyword . '%')";
} else {
$str .= "->orWhere('description', 'like', '%' . $keyword . '%')";
}
}
}
$str .= "->all()";
$items = Item::$str;
dd($items);
I need the value of $str to be appended to Item model, so that in effect the php interprets this as below
$items = Item::Where('description', 'like', '%' . 'laptop' . '%')->orWhere('description', 'like', '%' . 'pc' . '%')->all();
So that I can dynamically create where-clauses.
You are overcomplicating things a little here. Grab the collection of keywords, and iterate those, then use orWhere() on the keywords name, and voila. Open up a query on your items with the query() method, then apply orWhere() for each iteration. Laravel will handle the rest. Once done, you just need to get() your data!
$keywords = ProductKeyword::orderBy('name', 'asc')->get();
$items = Item::query();
foreach ($keywords as $key => $keyword) {
$items->orWhere('description', 'like', '%'.$keyword->name.'%');
}
$items = $items->get();
dd($items);
Note that if there are no keywords, it will essentially become Item::all(), since you do not apply any where-clauses.
you need to improve and fix your code:
$query = Item::query();
foreach ($keywords as $keyword) {
$query->orWhere('description', 'like', '%'.$keyword.'%');
}
$result=$query->get();
you are using a complex way to achieve it. my answer would be almost same as #Qirel
//prepare your query
$query = Item::query();
foreach ($keywords as $keyword) {
//loop through the keywords in the description column of Item Table match the records which will be available in the $query
$query->orWhere('description', 'like', '%'.$keyword.'%');
}
// get the records which are matched and store it in $result variable
$result=$query->get();`enter code here`
public static function searchSubmissions($request, $candidateIds = array(),$isscontact = NULL){
$querys = DB::table('submissions')->select('submissions.*');
if ( Input::has('candidatename') and $request->input('candidatename') != NULL){
$querys->join('candidates','candidates.candidateid','=','submissions.candidateid');
$querys->where('candidates.firstname', 'LIKE', '%'. $request->input('candidatename').'%')->orWhere('candidates.lastname', 'LIKE', '%'. $request->input('candidatename') .'%')->where('submissions.status','1');
}
$result = $querys->paginate(PAGELIMIT);
return $result ;
}
This is my search query if I entered "john" or "peter" in my search field it works fine. if I entered full name "john peter" it does not work for me.
In my database I have two fields 'firstname' 'lastname'
I think, you need to refactor your code to work it properly.
$names = explode(' ', $request->input('candidatename'));
if (!empty($names)) {
foreach ($names as $name) {
$querys = $querys->orWhere('candidates.firstname', 'LIKE', '%'. $name .'%');
$querys = $querys->orWhere('candidates.lastname', 'LIKE', '%'. $name .'%');
}
}
Have a look at this https://laravel.com/docs/5.4/queries#parameter-grouping
I'm currently trying to implement a search in my db for keywords. Therefore I split a string seperated by a comma, so I get an array containing a variable number of elements (one keyword).
I know that I can use a eloquent construct like that:
$products = Product::where([['keywords', 'LIKE', %samsung%], [keywords, 'LIKE', 's7']])->paginate(15);
to find a product with the keywords samsung,galaxy,s7.
Now I need this thing but automatically generated for a variable number of search query parts, so for every keyword in the array I need to add one ['keywords', 'LIKE', '...']...
How can I do this with Laravels Eloquent?
Use closure. First, make sure you stored list of keywords into array or the like. Then ...
$keywords = ['samsung', 's7', 'what else'];
$products = Product::where(function ($query) use ($keywords) {
foreach ($keywords as $keyword) {
$query->orWhere('keyword', 'like', $keyword);
}
})->paginate(15);
other example
$keywords = [
['name', 'LIKE', $searchQuery],
['category_id', '=', $selectedSubcategory],
];
$products = Product::where(function ($query) use ($keywords) {
foreach ($keywords as $keyword) {
$query->where($keyword);
}
})->paginate(15);
other than other
$keywords = [
['name', 'LIKE', $searchQuery],
['category_id', '=', $selectedSubcategory],
['please_id', '=', $learnPhpArray],
];
$products = Product::query();
foreach ($keywords as $keyword) {
$products = $products->where($keyword);
}
return $products->paginate(15);
What does the orWhere do? Does it connect the query parts with a AND?
No, with OR. As the inverse(?) the where itself does AND by default.
References
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_where
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_orWhere
Isn't it just to generate the array? Or am I misunderstanding the question?
<?php
$keys = ['samsung', 'lg', 'sony', 'nokia', 'apple'];
$keywords = [];
foreach($keys as $key){
$keywords[] = ['keywords', 'LIKE', '%'.$key.'%'];
}
$products = Product::where($keywords)->paginate(15);
You can do this:
$query = "Samsung galaxy S7"; // Or whatever the query is
$words = preg_split("/[ ,.]/",$query); //Split on space comma or dot. Maybe need more?
$queries = array_map(function ($word) {
return [ "keywords", "LIKE", "%$word%" ];
}, $words); //Transform single words to array of queries
$products = Product::where($queries)->paginate(15);
Check how the first part of the code works at: https://eval.in/730772
laravel 5.6
$keyWords = KeyWordModel::all();
$keyWordQuerys = [];
foreach ($keyWords as $key => $item) {
$keyWordQuerys[$key] = ['title', 'like', '%'.$item->name.'%'];
}
$contents = ContentModel::query();
foreach ($keyWordQuerys as $key => $item) {
$contents = $contents->orwhere([$item]);
}
$contents = $contents->orderBy('pubDate', 'DESC')->get();
I am trying to create a way for users to search through all the products on a website. When they search for "burton snowboards", I only want the snowboards with the brand burton to appear in the results. But if they searched only "burton", then all products with the brand burton should appear.
This is what I have attempted to write but isn't working for multiple reasons.
Controller:
public function search(){
$input = Input::all();
$v= Validator::make($input, Product::$rules);
if($v->passes())
{
$searchTerms = explode(' ', $input);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)){
$searchTermBits[] = "search LIKE '%$term%'";
}
}
$result = DB::table('products')
->select('*')
->whereRaw(". implode(' AND ', $searchTermBits) . ")
->get();
return View::make('layouts/search', compact('result'));
}
return Redirect::route('/');
}
I am trying to recreate the first solution given for this stackoverflow.com problem
The first problem I have identified is that i'm trying to explode the $input, but it's already an array. So i'm not sure how to go about fixing that. And the way I have written the ->whereRaw(". implode(' AND ', $searchTermBits) . "), i'm sure isn't correct. I'm not sure how to fix these problems though, any insights or solutions will be greatly appreciated.
You'll need to get the terms from your input field and loop through all of them while building your DB query. You'll also need to set the table field in which you want the terms to be searched, in this the example the table field is name. Here's an untested example but you'll get the idea.
public function search() {
$q = Input::get('myInputField');
$searchTerms = explode(' ', $q);
$query = DB::table('products');
foreach($searchTerms as $term)
{
$query->where('name', 'LIKE', '%'. $term .'%');
}
$results = $query->get();
}
I made a plugin for laravel to make this! Hope you use it and give feedback.
You can specify the relevance for each column and use information from other tables
https://github.com/nicolaslopezj/searchable
You can search like this
$products = Product::search($query)->get();
Controller Function 1
public function search() {
$q = Input::get('searchKeyWords');
$users = DB::table('users');
$results = $users->where('name', 'LIKE', '%'. $q .'%')
->orWhere('email', 'LIKE', '%'. $q .'%')
->orWhere('password', 'LIKE', '%'. $q .'%')
->get();
return View::make('users.search')->with('users', $results);
}
Controller Function 2
public function search() {
$q = Input::get('searchKeyWords');
$results = User::where('name', 'LIKE', '%'. $q .'%')
->orWhere('email', 'LIKE', '%'. $q .'%')
->orWhere('password', 'LIKE', '%'. $q .'%')
->get();
return View::make('users.search')->with('users', $results);
}
Controller Function 3
public function search() {
$results = User::where('name', 'LIKE', '%'. Input::get('searchKeyWords') .'%')
->orWhere('email', 'LIKE', '%'. Input::get('searchKeyWords') .'%')
->orWhere('password', 'LIKE', '%'. Input::get('searchKeyWords') .'%')
->get();
return View::make('users.search')->with('users', $results);
}
This is sample when I try using Eloquent with many search terms
public function search() {
$q = Input::get('myInputField');
$searchTerms = explode(' ', $q);
$query = $article->where('title', 'LIKE', "%{$keyword}%")
->orWhere('description', 'LIKE', "%{$keyword}%");
foreach($searchTerms as $term)
{
$query = $query->orWhere('name', 'LIKE', '%'. $term .'%');
}
$results = $query->get();
}
You can also change ->get() function to other results like ->paginate(), and it should be like $results = $query->paginate(10);