Search Query not functioning properly in Laravel - php

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

Related

php get variable value and append it to a query in a dynamic manner

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`

Eloquent - multiple WHERE LIKE conditions

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();

Wildcards and Like on Laravel Error not working on $variable

So I have this code
$Input = Input::all();
$makethis = Input::flash();
$soptions = Input::get('soptions');
$items = Gamefarm::where('roost_hen', '=',Input::get('sex'))
->where('bname', 'LIKE', '%$soptions%')
->paginate(6);
What I want to do is for laravel to accept the value inside the $soptions. When I tried hard coding the $soptions it works fine.
One more question
$Input = Input::all();
$makethis = Input::flash();
$textbox = Input::get('searchbox');
$soptions = Input::get('soptions');
var_dump($soptions);
$items = Gamefarm::where('roost_hen', '=', Input::get('sex'))
->where($soptions, 'LIKE', "$textbox")
->paginate(6);
return View::make('gamefarms/index', compact('items','makethis'));
Now what I want to do is use the variable $soptions to be the query's field name, I get an error 500 when I do this
This '%$soptions%' does not get interpolated, instead you should write "%$soptions%" or "%{$soptions}%" or '%' . $soptions . '%'. Simple mistake.

creating a search feature in Laravel 4

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);

Creating search functionality with Laravel 4

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);

Categories