Creating search functionality with Laravel 4 - php

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

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`

Search Query not functioning properly in Laravel

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

When fetching data from table "add_hotels" but along with the required data i'm also getting some NULL arrays in Laravel

It is the result function inside the HotelController.
public function result()
{
$data=Input::except(array('_token'));
$city= $data['city'];
$cities_id = DB::table('cities')
->select('id')
->where('cities.city_name', 'LIKE', "%$city%")
->get();
$hotel = array();
foreach ($cities_id as $value) {
$i=$value->id;
$hotel[] = DB::table('add_hotels')
->select('id')
->where('city_id', '=', $i)
->get();
}
var_dump($hotel);
exit();
return view('hotel.result',compact('hotel','city'));
}
This is the result which i'm getting, but I required only data marked by red color box
Try this query:
$cities_id = DB::table('cities')
->where('cities.city_name', 'LIKE', "%$city%")
->Join('add_hotels','add_hotels.city_id','=','cities.id')
->select('add_hotels.id')
->get();
var_dump($cities_id);

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

Categories