Laravel advance search - laravel

I have created a multiform search in laravel & it's not working properly
I have a table name candidates & there is a row named salary in which it has value like shown the the below image from 1 lac(s) to 39 lac(s)
The meaning it's not working properly is if i search min salary = 0 & max salary = 4 it's showing data between 0 to 4 but it's also showing data like 10 18 22
controller code
public function advance(Request $request)
{
$data = \DB::table('candidates');
if( $request->name){
$data = $data->where('name', 'LIKE', "%" . $request->name . "%");
}
if( $request->location){
$data = $data->where('location', 'LIKE', "%" . $request->location . "%");
}
if( $request->key_skills){
$data = $data->where('key_skills', 'LIKE', "%" . $request->key_skills . "%");
}
if( $request->gender){
$data = $data->where('gender', 'LIKE', "%" . $request->gender . "%");
}
if( $request->pref_loc){
$data = $data->where('pref_loc', 'LIKE', "%" . $request->pref_loc . "%");
}
if( $request->phoneno){
$data = $data->where('phoneno', 'LIKE', "%" . $request->phoneno . "%");
}
if( $request->email){
$data = $data->where('email', 'LIKE', "%" . $request->email . "%");
}
$min_ctc = $request->min_ctc;
$max_ctc = $request->max_ctc;
if ($min_ctc || $max_ctc) {
$data = $data->where('salary', '>=', $min_ctc);
$data = $data->where('salary','<=',$max_ctc);
}
$data = $data->paginate(10);
$data2 = $data->total();
return view('search', compact('data2'))->with('data',$data);
}
Thanks in advance

You are trying to search on string not on integer. In order to get the required result you have to type cast the string to integer or float and then perform the operation.
Here is the script that might help you.
if ($min_ctc || $max_ctc) {
$data = $data->whereRaw("CONVERT(SUBSTRING_INDEX(salary,' ', 1),UNSIGNED INTEGER) >= {$min_ctc}");
$data = $data->whereRaw("CONVERT(SUBSTRING_INDEX(salary,' ', 1),UNSIGNED INTEGER) <= {$max_ctc}");
}

Related

Laravel 5.2 orWhere generate "and" in query

I have written a query in Laravel 5.2 as below, where I used scope. The scope scopeSubscriberCriteriaSearch have further sub scope. The scenario is, if the main scope finds "first_name" "=" "test" OR "last_name" "!=" "demo" etc, the related sub scope will be called.
$record = self::leftJoin("$customersTable as customers", 'customers.email', '=', "{$this->table}.email")
->leftJoin("$campaignsTable as campaigns", 'campaigns.campaign_id', '=', "{$this->table}.campaign_id")
->select("$this->primaryKey", "{$this->table}.first_name", "{$this->table}.last_name", "{$this->table}.email", "{$this->table}.phone", "{$this->table}.address", "campaigns.campaign_id", "campaigns.campaign_name", "customers.order_count")
->whereRaw($where);
$record->subscriberCriteriaSearch($criteria, $search_type, $persist)
->searchAfter($waiting_min, $search_type, $this->user_id)
->excludeLeadEmail($last_used_email)
->greaterCreateDateSearch($campaign_start_date)
->get();
===========
The main scope is as below:
public function scopeSubscriberCriteriaSearch($query, $criteria, $search_type, $persist = TRUE)
{
if (!empty($criteria))
{
$criteria_var = ['first_name', 'last_name', 'email', 'phone_number', 'city', 'country', 'state', 'zip', 'address', 'campaign', 'affiliate', 'subAffiliate', 'createdAt'];
return $query->where(function($sub_query) use ($criteria, $criteria_var, $search_type, $persist)
{
foreach ($criteria as $rule)
{
if (in_array($rule->condition, $criteria_var))
{
$position = array_search($rule->condition, $criteria_var);
($rule->condition == 'affiliate' || $rule->condition == 'subAffiliate') ? $sub_query->{$criteria_var[$position] . 'Search'}($rule->logical, $rule->input_val, $search_type, $persist) : $sub_query->{$criteria_var[$position] . 'Search'}($rule->logical, $rule->input_val, $persist);
}
}
});
}
}
The sub scopes (for example:) as below:
public function scopeFirst_nameSearch($query, $operator, $first_name, $persist = TRUE)
{
$query_operator = $this->getQueryOperator($operator);
if (!empty($operator) && !empty($first_name))
{
$query_operator_val = preg_match('/like/i', $query_operator) ? ($operator == 'starts' ? '"' . $first_name . '%"' : ($operator == 'ends' ? '"%' . $first_name . '"' : '"%' . $first_name . '%"')) : '"' . $first_name . '"';
return $persist ? $query->where($this->table . ".first_name", $query_operator, DB::raw($query_operator_val)) : $query->orWhere($this->table . ".first_name", $query_operator, DB::raw($query_operator_val));
}
}
public function scopeLast_nameSearch($query, $operator, $last_name, $persist = TRUE)
{
$query_operator = $this->getQueryOperator($operator);
if (!empty($operator) && !empty($last_name))
{
$query_operator_val = preg_match('/like/i', $query_operator) ? ($operator == 'starts' ? '"' . $last_name . '%"' : ($operator == 'ends' ? '"%' . $last_name . '"' : '"%' . $last_name . '%"')) : '"' . $last_name . '"';
return $persist ? $query->where($this->table . ".last_name", $query_operator, DB::raw($query_operator_val)) : $query->orWhere($this->table . ".last_name", $query_operator, DB::raw($query_operator_val));
}
}
So, if $persist is False, then the orWhere part of these sub queries will execute. But in my case, the query now generated as below:
select prospect_id, sem_1_prospects.first_name, sem_1_prospects.last_name, sem_1_prospects.email, sem_1_prospects.phone, sem_1_prospects.address, sem_campaigns.campaign_id, sem_campaigns.campaign_name, sem_customers.order_count from sem_1_prospects left join sem_1_customers as sem_customers on sem_customers.email = sem_1_prospects.email left join sem_1_campaigns as sem_campaigns on sem_campaigns.campaign_id = sem_1_prospects.campaign_id where ((sem_1_prospects.first_name = "test") and (sem_1_prospects.last_name NOT LIKE "%demo%"));
Can someone help me to find out the issue?

How to create api for search in lumen/laravel?

How to create api for search in lumen/laravel .. I tried using keyword but not working.
public function index(){
$Employees = Employees::all();
$page = Input::get('page', 1);
$keyword = Input::get('keyword', '');
if ($keyword!='') {
$keyword = Employees::
where("firstname", "LIKE","%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%");
}
$itemPerPage=5;
$count = Employees::count();
$offSet = ($page * $itemPerPage) - $itemPerPage;
$itemsForCurrentPage = array_slice($Employees->toArray(), $offSet, $itemPerPage);
return new LengthAwarePaginator($itemsForCurrentPage, count($Employees), $itemPerPage, $page,$keyword);
}
You should change this line :
if ($keyword!='') {
$Employees = Employees::
where("firstname", "LIKE","%$keyword%")
->orWhere("lastname", "LIKE", "%$keyword%")
->get();
}
Also i think You should the pagination within the model query, not on the returned result.
you can also do this
define your logic in a scope created in you model and consume it in your controller.here is what i mean
This should be in your model
public function scopeFilter($query, $params)
{
if ( isset($params['name']) && trim($params['name'] !== '') )
{
$query->where('name', 'LIKE', trim($params['name']) . '%');
}
if ( isset($params['state']) && trim($params['state'] !== '') )
{
$query->where('state', 'LIKE', trim($params['state']) . '%');
}
return $query;
}
and in your controller have something like
public function filter_property(Request $request)
{
$params = $request->except('_token');
$product = Product::filter($params)->get();
return response($product);
}
you can get more by reading scope on laravel doc and this blog post here

How to write laravel model based in this query with pagination?

for ($i = 0; $i < count($keyskill); $i++) {
if ($i == count($keyskill) - 1) {
$key .= "skills like '%" . $keyskill[$i] . "%' ";
} else {
$key .= "skills like '%" . $keyskill[$i] . "%' or ";
}
}
Hear my Query is
$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");
How to write laravel model based in this query with pagination???
Post::where('skills' , 'like' , '%php%')->orWhere('skills' , 'like' , '%javascript%')->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);
try this for dynamic array:
Post::where(function ($query) use ($keyskill) {
for ($i = 0; $i < count($keyskill); $i++) {
if ($i == 0) {
$query->where('skills' , 'like' ,"%$keyskill[$i]%");
} else {
$query->orWhere('skills' , 'like' , "%$keyskill[$i]%");
}
}
})->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);
Below is the Eloquent Query considering Post as your Model Name and Page Size 50.
$posts = \App\Post::where('skills','like','%javascript%')
->orWhere('skills','like','%php%')
->where('status',1)
->orderBy('id','desc')
->paginate(50);
Loading records
$posts->items();
Rendering Pagination on Blade
{!! $posts->render() !!}
Just a recommendation
Your table name should be posts instead or post then Laravel can manage it implicitly but in your case currently you will have to mention the table name in your model with code protected $table = 'post'; in your app/post.php file, read more here.

Exporting 4000+ members details to pdf not rendering the data in laravel 5.2

I am using an export function in my controller inorder to export the details of 4000+ members in doc and pdf format. At first the error shown as memory exhausted. So I wrote ini_set('memory_limit', '-1'); at the beginning of my function. Now the document works fine, but still export to pdf not working. The below is my function I wrote in laravel 5.2 controller.
protected function export() {
ini_set('memory_limit', '-1');
$members = MembersModel::select();
$sortBy = Request::get('sort');
switch ($sortBy) {
case 'name':
$members->orderBy('name');
break;
case 'member_num':
$members->orderBy('member_num');
break;
case 'address':
$members->orderBy('address');
break;
case 'road':
$members->orderBy('road');
break;
case 'pincode':
$members->orderBy('pincode');
break;
case 'city':
$members->orderBy('city');
break;
default:
# code...
break;
}
$filter = Request::get('filter');
if($filter != '') {
$members->where('name', 'like', '%' . $filter . '%')->orWhere('member_num', 'like', '%' . $filter . '%')->orWhere('address', 'like', '%' . $filter . '%')->orWhere('address2', 'like', '%' . $filter . '%')->orWhere('road', 'like', '%' . $filter . '%')->orWhere('city', 'like', '%' . $filter . '%')->orWhere('pincode', 'like', '%' . $filter . '%')->orWhere('blood_group', 'like', '%' . $filter . '%')->orWhere('land_num', 'like', '%' . $filter . '%')->orWhere('mob_num', 'like', '%' . $filter . '%')->orWhere('occupation', 'like', '%' . $filter . '%');
}
$members = $members->get();
$data = array('members' => $members);
$type = Request::get('type');
switch ($type) {
case 'doc':
$view = View::make('allmembers.exportdoc', $data);
$contents = $view->render();
// or
$contents = (string) $view;
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=allmembers.doc");
echo $contents;
break;
case 'pdf':
$pdf = PDF::loadView('allmembers.exportdoc', $data);
return $pdf->download('allmembers.pdf');
break;
default:
# code...
break;
}
}
What might be the issue. Thanks in advance.

How to route a query string in a codeigniter Search?

I have a question with route a query string.
I'm trying to route with codeigniter a search. I have some parameters for each search, first a input text field, for a title or a description. Second, I have categories like, Utilities, Games, Exercise... Third, a platform, like, IOS, WP, Android.. and also the page.
I would like to see the route like:
/page/3, or
/page/3/search/whatever or
/cat/Games or
/cat/Games/search/battelfield or
/page/1/cat/games/search/battelfield or
/search/whatever or something like that.
I am using this code for the function in the model:
enter code here
function getAppBy($categ, $page, $str, $platform) {
$perpage = 16;
$offset = ($page-1)*$perpage;
$this->db->select('app.id');
$this->db->from('t_yp_app_category cat, t_yp_user_apps app');
if ($categ != "") {
$this->db->where("cat.name =", $categ);
} if ($str != "") {
$this->db->like('app.yp_title', '%' . $str . '%');
$this->db->like('app.yp_description', '%' . $str . '%');
}if ($platform != "") {
$this->db->like('app.yp_platforms', '%' . $platform . '%');
}
$this->db->limit($perpage,$offset);
$query = $this->db->get();
$result = $query->result_array();
//FIN SELECT
if (sizeof($result) > 0) {
return $result;
} else {
return false;
}
}
enter code here
Thank you. If I havent explained well, let me know
//www.mysite.com/search/sometitle/puzzle/android/4
$route['search/(:any)/(:any)/(:any)'] = 'search/getAppby/$1/$2/$3'; //default without offset, which is why offset defaults to 0
$route['search/(:any)/(:any)/(:any)/(:num)'] = 'search/getAppby/$1/$2/$3/$4'; //default with offset
//You may want to use some regex rather than wildcards ie:(:any)
public function getAppBy($input, $category, $platform, $offset=0){}

Resources