Laravel search with multiple conditions - laravel

I am performing a search in table with multiple condition which can exist individually and in group. These are my codes for the process.
Controller Code
if(\Input::has('title','category_id','type','price_max','price_min','seller_type_id','division_id','district_id','upazila_id')) {
$data['products'] = Custom::getProducts(\Input::get('title'), \Input::get('category_id'), \Input::get('type'),\Input::get('price_max'),\Input::get('price_min'),\Input::get('seller_type_id'),\Input::get('division_id'),\Input::get('district_id'),\Input::get('upazila_id'));
} else {
$data['products'] = \DB::table('products')->where('is_active', '=', 1)->get();
}
return view('pages.posts.list')->with($data);
Custom::getProducts
public static function getProducts($title = NULL, $category_id = NULL, $type = 0, $price_max = NULL, $price_min = NULL, $seller_type_id = 0, $division_id = NULL, $district_id = NULL, $upazila_id = NULL) {
$products = DB::table('products')
->where(function($query) use ($title, $category_id, $type, $price_max, $price_min, $seller_type_id, $division_id, $district_id, $upazila_id) {
if ($title)
$query->where('title', 'like', $title);
if ($category_id)
$query->where('category_id', $category_id);
if ($type != 0)
$query->where('type', $type);
if ($price_max)
$query->where('price', '<=', $price_max);
if ($price_min)
$query->where('price', '>=', $price_min);
if ($seller_type_id != 0)
$query->where('seller_type_id', $seller_type_id);
if ($division_id)
$query->where('division_id', $division_id);
if ($district_id)
$query->where('district_id', $district_id);
if ($upazila_id)
$query->where('upazila_id', $upazila_id);
})
->where('is_active', '=', 1)->get();
return $products;
}
But it is not working as expected. What I am doing wrong?

Related

Laravel Data table : Getting SQLSTATE[42S22]: Column not found: 1054 Unknown column error

Here is my data table query funciton.
/**
* #param ProjectTimeLog $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(ProjectDailyStandup $model)
{
$request = $this->request();
$projectId = $request->projectId;
$employee = $request->employee;
$taskId = $request->taskId;
$approved = $request->approved;
$invoice = $request->invoice;
$model = $model->with('user', 'user.employeeDetail', 'user.employeeDetail.designation', 'user.session', 'project', 'task');
$model = $model->join('users', 'users.id', '=', 'project_time_logs.user_id')
->join('employee_details', 'users.id', '=', 'employee_details.user_id')
->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id')
->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id')
->leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id');
$model = $model->select('project_time_logs.id','project_time_logs.project_id','project_time_logs.start_time', 'project_time_logs.end_time', 'project_time_logs.total_hours', 'project_time_logs.total_minutes', 'project_time_logs.memo', 'project_time_logs.user_id', 'project_time_logs.project_id', 'project_time_logs.task_id', 'users.name', 'users.image', 'project_time_logs.hourly_rate', 'project_time_logs.earnings', 'project_time_logs.approved', 'tasks.heading','tasks.due_date', 'projects.project_name', 'designations.name as designation_name', 'project_time_logs.added_by','project_time_logs.flag as flagId');
if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') {
$startDate = Carbon::createFromFormat($this->global->date_format, $request->startDate)->toDateString();
if (!is_null($startDate)) {
$model->where(DB::raw('DATE(project_time_logs.`start_time`)'), '>=', $startDate);
}
}
if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') {
$endDate = Carbon::createFromFormat($this->global->date_format, $request->endDate)->toDateString();
if (!is_null($endDate)) {
$model->where(function ($query) use ($endDate) {
$query->where(DB::raw('DATE(project_time_logs.`end_time`)'), '<=', $endDate);
});
}
}
if (!is_null($employee) && $employee !== 'all') {
$model->where('project_time_logs.user_id', $employee);
}
if (!is_null($projectId) && $projectId !== 'all') {
$model->where('project_time_logs.project_id', '=', $projectId);
}
if (!is_null($taskId) && $taskId !== 'all') {
$model->where('project_time_logs.task_id', '=', $taskId);
}
if (!is_null($approved) && $approved !== 'all') {
if ($approved == 2) {
$model->whereNull('project_time_logs.end_time');
}
else {
$model->where('project_time_logs.approved', '=', $approved);
}
}
if (!is_null($invoice) && $invoice !== 'all') {
if ($invoice == 0) {
$model->whereNull('project_time_logs.invoice_id');
}
else if ($invoice == 1) {
$model->whereNotNull('project_time_logs.invoice_id');
}
}
if ($request->searchText != '') {
$model->where(function ($query) {
$query->where('tasks.heading', 'like', '%' . request('searchText') . '%')
->orWhere('project_time_logs.memo', 'like', '%' . request('searchText') . '%')
->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%');
});
};
if ($this->viewTimelogPermission == 'added') {
$model->where('project_time_logs.added_by', user()->id);
}
if ($this->viewTimelogPermission == 'owned') {
$model->where(function ($q) {
$q->where('project_time_logs.user_id', '=', user()->id);
if (in_array('client', user_roles())) {
$q->orWhere('projects.client_id', '=', user()->id);
}
});
}
if ($this->viewTimelogPermission == 'both') {
$model->where(function ($q) {
$q->where('project_time_logs.user_id', '=', user()->id);
$q->orWhere('project_time_logs.added_by', '=', user()->id);
if (in_array('client', user_roles())) {
$q->orWhere('projects.client_id', '=', user()->id);
}
});
}
return $model;
}
It is giving me this error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'project_time_logs.user_id' in 'on clause' (SQL: select count(*) as aggregate from `project_daily_standups` inner join `users` on `users`.`id` = `project_time_logs`.`user_id` inner join `employee_details` on `users`.`id` = `employee_details`.`user_id` left join `designations` on `employee_details`.`designation_id` = `designations`.`id` left join `project_time_logs` on `project_time_logs`.`user_id` = `users`.`id` left join `tasks` on `tasks`.`id` = `project_time_logs`.`task_id` left join `projects` on `projects`.`id` = `project_time_logs`.`project_id`)
Please help
I was expecting a working data table
I figured out that I was referring to the wrong model in the query function so I solved it by importing the right model.
public function query(ProjectTimeLogs $model)
Thank you!

How can add condition on requette contoller in laravl

if ($id_ville != null) {
$queryCondition .= "where('annonces.id_ville','=',$id_ville)";
}
if ($id_marque != null) {
if ($queryCondition != null) {
$queryCondition .= "->where";
} else {
$queryCondition .= "where";
}
$queryCondition .= "('annonces.id_marque','=',$id_marque)";
}
if ($id_modele != null) {
if ($queryCondition != null) {
$queryCondition .= "->where";
} else {
$queryCondition .= "where ";
}
$queryCondition .= " ('annonces.id_modele','=',$id_modele)";
}
$annonce = Annonce::select('*', 'annonces.id as idA', 'annonces.created_at as createdAt')
->join('marques', 'marques.id', '=', 'id_marque')
->join('modeles', 'modeles.id', '=', 'id_modele')
->join('villes', 'villes.id', '=', 'id_ville')
->join('boitevitesses', 'boitevitesses.id', '=', 'id_boite')
->join('annees', 'annees.id', '=', 'id_annee')
->join('typecarburants', 'typecarburants.id', '=', 'id_type')
->$queryCondition->paginate(12);
**please help me it's working in php but in laravel not worked i have this probleme Property [where('annonces.id_ville','=',1)] does not exist on the Eloquent builder instance.
**
$annonce = Annonce::select(......
if ($id_ville != null) {
$annonce->where(......);
}
if (...) {
$annonce->where(.....);
}
$announce->paginate(12);
create db instace from model
$dbInstace = Annonce::select('*', 'annonces.id as idA', 'annonces.created_at as createdAt')
->join('marques', 'marques.id', '=', 'id_marque')
->join('modeles', 'modeles.id', '=', 'id_modele')
->join('villes', 'villes.id', '=', 'id_ville')
->join('boitevitesses', 'boitevitesses.id', '=', 'id_boite')
->join('annees', 'annees.id', '=', 'id_annee')
->join('typecarburants', 'typecarburants.id', '=', 'id_type');
like this then
add condition
if ($id_ville != null) {
$dbInstace->where('annonces.id_ville','=',$id_ville);
}
$announce = $dbInstace->paginate(12);
Try as below.
$annonce = Annonce::select('*', 'annonces.id as idA', 'annonces.created_at as createdAt')
->join('marques', 'marques.id', '=', 'id_marque')
->join('modeles', 'modeles.id', '=','id_modele')
->join('villes', 'villes.id', '=', 'id_ville')
->join('boitevitesses','boitevitesses.id', '=', 'id_boite')
->join('annees', 'annees.id', '=', 'id_annee')
->join('typecarburants', 'typecarburants.id', '=', 'id_type');
if($id_ville != null) {
$annonce = $annonce->where('annonces.id_ville',$id_ville);
}
if($id_marque != null) {
$annonce = $annonce->where('annonces.id_marque',$id_marque);
}
if($id_modele != null) {
$annonce = $annonce->where('annonces.id_modele',$id_modele);
}
$annonce = $annonce->paginate(12);

Eloquent - multiple 'when' conditions in query

I create query dependent for multiple parameters. When controller function get for example 'price' and 'status' parameter I want to return results based on that two parameters.
When I use one parameter everything works well.
There is example of my controller.
$productList = Product::
where([
['lat', '>', $calculateDistanceDifference->getData()->latDifferenceBottom],
['lat', '<', $calculateDistanceDifference->getData()->latDifferenceTop],
['lng', '>', $calculateDistanceDifference->getData()->lngDifferenceBottom],
['lng', '<', $calculateDistanceDifference->getData()->lngDifferenceTop]
])
->when(request('price') !== "", function ($q) {
if(request('price') === "0-20"){
return $q->where([['price', '>', 0], ['price', '<=', 20]]);
}else if(request('price') === "21-50"){
return $q->where([['price', '>', 20], ['price', '<=', 50]]);
}else if(request('price') === "51-100"){
return $q->where([['price', '>', 50], ['price', '<=', 100]]);
}else if(request('price') === "100-200"){
return $q->where([['price', '>', 100], ['price', '<=', 200]]);
}else if(request('price') === "201+"){
return $q->where('price', '>', 200);
}
})
->when(request('status') !== "", function ($q) {
if(request('status') === "new"){
return $q->where('status', 0);
}else if(request('status') === "old"){
return $q->where('status', 1);
}
})
->when(request('active') !== "", function ($q) {
if(request('active') == true){
return $q->where('state', 0);
}else{
var_dump(request('active'));
return $q->where('state', 1);
}
})
->with('productPhotos')
->with('categories')
->with('users')
->get();
How can I avoid return statements and return result after all transformations?
I appreciate any help.
You can split and merge the query by if/else or any programming statement.
For example
$productList = Product::select('*');
if (request('price') !== ""){
if(request('price') === "0-20"){
$productList = $productList->where('price', '>', 0)->where('price', '<=', 20);
}
//any other conditions that you want to handle....
}
if (request('status') !== ""){
if(request('status') === "new){
$productList = $productList->where('status', '=', 0);
}
//any other conditions that you want to handle....
}
$productList = $productList
->with('productPhotos')
->with('categories')
->with('users')
->get();
Hope this help.

Count with join still not displaing correct count

What I am trying to do is create a list of how many replies this thread has. I can count the number of replys fine.
But what I would like to be able to do is count the user thread also.
This is what the out put looks like. It only counts it from my replys table cannot seem to get it to count from my join as well.
Username Post
demo 2
admin 1
Should out put like
Username Post
demo 3 <-- Because the user has asked the Question / "thread" and has replied twice
admin 1
Question How to make sure it can count the user id from the join() thread table?
Model function
public function number_of_replies($user_id, $thread_id) {
$this->db->select('*');
$this->db->from('reply');
$this->db->join('thread', 'thread.user_id = reply.user_id', 'left');
$this->db->where('reply.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
} else {
return 0;
}
}
Controller
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index($thread_id = '') {
$data['users'] = array();
$data['thread_id'] = $thread_id;
$results = $this->get_users_who_replied($thread_id);
if (isset($results)) {
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'total' => $this->number_of_replies($result['user_id'], $thread_id),
);
}
}
$data['total_posts'] = '';
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
public function get_users_who_replied($thread_id) {
$this->db->select('user.username, user.user_id, reply.thread_id');
$this->db->distinct();
$this->db->from('reply');
$this->db->join('user', 'user.user_id = reply.user_id', 'left');
$this->db->join('thread', 'thread.user_id = user.user_id', 'left');
$this->db->where('reply.thread_id', $thread_id);
$this->db->order_by('thread.user_id', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
public function number_of_replies($user_id, $thread_id) {
$this->db->select('*');
$this->db->from('reply');
$this->db->join('thread', 'thread.user_id = reply.user_id', 'left');
$this->db->where('reply.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
} else {
return 0;
}
}
}
Thread Table
Reply Table
Do sum 2 tables user_id columns
public function number_of_replies($user_id, $thread_id) {
$this->db->select('t1.*, count(t2.user_id)+count(t1.user_id) AS total_posts');
$this->db->from('reply AS t1');
$this->db->join('thread AS t2', 't2.user_id = t1.user_id', 'left');
$this->db->where('t1.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->num_rows();
} else {
return 0;
}
}
I seem to have got it working mostly now bit more testing to do
What I have had to do is create to functions for counting one for replies and one for threads
public function replies_by_users($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('reply');
}
public function thread_by_user($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('thread');
}
Then combine them and using plus + and then return it
public function total_replies_and_thread($user_id, $thread_id) {
return $this->replies_by_users($user_id, $thread_id) + $this->thread_by_user($user_id, $thread_id);
}
And then use the total_replies_and_thread($user_id, $thread_id) in the array itself like
$results = $this->get_replies($thread_id);
if ($results) {
foreach ($results as $result) {
$data['users'][] = array(
'reply_id' => $result['reply_id'],
'user_id' => $result['user_id'],
'thread_id' => $result['thread_id'],
'username' => $result['username'],
'total' => $this->total_replies_and_thread($result['user_id'], $result['thread_id'])
);
}
}
Out put now correct
Controller HMVC
<?php
class Who_replied extends MX_Controller {
public function __construct() {
parent::__construct();
}
public function index($user_id, $thread_id) {
$data['users'] = array();
$results = $this->get_replies($thread_id);
if ($results) {
foreach ($results as $result) {
$data['users'][] = array(
'reply_id' => $result['reply_id'],
'user_id' => $result['user_id'],
'thread_id' => $result['thread_id'],
'username' => $result['username'],
'total' => $this->total_replies_and_thread($result['user_id'], $result['thread_id'])
);
}
}
$data['user_id'] = $user_id;
return $this->load->view('default/template/forum/categories/who_replied_view', $data);
}
// Model code is just on here for testing purpose you should all ways create a model for it self.
public function get_replies($thread_id) {
$this->db->select('reply.*, user.username');
$this->db->from('reply');
$this->db->join('user', 'user.user_id = reply.user_id');
$this->db->where('thread_id', $thread_id);
$this->db->group_by('user_id');
$this->db->order_by('thread_id', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
public function total_replies_and_thread($user_id, $thread_id) {
return $this->replies_by_users($user_id, $thread_id) + $this->thread_by_user($user_id, $thread_id);
}
public function replies_by_users($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('reply');
}
public function thread_by_user($user_id, $thread_id) {
$this->db->where('user_id', $user_id);
$this->db->where('thread_id', $thread_id);
return $this->db->count_all_results('thread');
}
}

Best Practice: Models and Controllers

I would like to get your MVC experience on the following:
I have a table where I say which user_id is in which group_id and a second table where I say which user_id has which user_name.
Now I want a function to which I pass a group_id and it gives me all user_names in the group.
The question is, what does the Controller do and what the Model:
Controller calls a Model (get_user_ids_from_group) that returns the user ids and then the controler calls different model (get_user_name_by_id) to return the usernames.
A controller calls a Model (`get_user_names_from_group) and the model internally gets first the user ids and then the user names.
I understand that the first way is more MVC strict. But how strict would you be in a case like this? Right now I am always being very strict.
As a result my model functions have always just two lines (query and return) and my controller are bigger. So to make controller and model size more equal the second option would be possible.
Actually, it has nothing to do with MVC, as CodeIgniter doesn't implement MVC, but a sort of MVP.
However, if you're using RDBMS such as MySQL, you could JOIN these two table (within the Model) and fetch the result (within the Controller) as I suggested in a similar topic on SO.
application/models/user.php
class User extends CI_Model
{
public function get_users_by_group($group_id)
{
$this->db->select('*')->from('groups');
// While group_id and user_id have a N:1 relation
$this->db->where('group_id', $group_id);
$this->db->join('users', 'users.user_id = groups.user_id');
$query=$this->db->get();
return $query->result_array();
}
}
Then fetch and pass the result within the Controller:
application/controllers/users.php
class Users extends CI_Controller
{
public function view($group_id)
{
$this->load->model('user');
// Fetch the result from the database
$data['users'] = $this->user->get_users_by_group($group_id);
// Pass the result to the view
$this->load->view('users_view', $data);
}
}
In MVC model should not be only use for storing and getting the data but also it should contain the business logic.
Controller - Should take input communicate with model and view
Model - Should contain business logic and data store
View - Only for Output
So its like Input -> Process -> Output
Also its depend on you where to put what and you should have a balance code on controller and model, Not write everything in controller or in model
In you case I think you should uses get_user_names_from_group and just pass the group name and make a join query between two table. And when you define your function in the model its give you the option to reuse the function again in case you need same thing on next controller.
Common model example:
<?php
class Common_model extends CI_Model {
function get_entry_by_data($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '') {
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function get_entry_by_data_in($table_name, $single = false, $data = array(), $select = "", $order_by = '', $orderby_field = '', $limit = '', $offset = 0, $group_by = '',$in_column='',$in_data=''){
if (!empty($select)) {
$this->db->select($select);
}
if (empty($data)) {
$id = $this->input->post('id');
if (!$id)
return false;
$data = array('id' => $id);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
if (!empty($limit)) {
$this->db->limit($limit, $offset);
}
if (!empty($order_by) && !empty($orderby_field)) {
$this->db->order_by($orderby_field, $order_by);
}
if (!empty($in_data) and !empty($in_column)) {
$this->db->where_in($in_column,$in_data);
}
$query = $this->db->get_where($table_name, $data);
$res = $query->result_array();
//echo $this->db->last_query();exit;
if (!empty($res)) {
if ($single)
return $res[0];
else
return $res;
} else
return false;
}
public function getAllRecords($table, $orderby_field = '', $orderby_val = '', $where_field = '', $where_val = '', $select = '', $limit = '', $limit_val = '') {
if (!empty($limit)) {
$offset = (empty($limit_val)) ? '0' : $limit_val;
$this->db->limit($limit, $offset);
}
if (!empty($select)) {
$this->db->select($select);
}
if ($orderby_field)
$this->db->order_by($orderby_field, $orderby_val);
if ($where_field)
$this->db->where($where_field, $where_val);
$query = $this->db->get($table);
//return $query->num_rows;
//echo $this->db->last_query();
if ($query->num_rows > 0) {
return $query->result_array();
}
}
function alldata($table) {
$query = $this->db->get($table);
return $query->result_array();
}
function alldata_count($table, $where) {
$query = $this->db->get_where($table, $where);
return $query->num_rows();
}
function insert_entry($table, $data) {
$this->db->insert($table, $data);
return $this->db->insert_id();
}
function update_entry($table_name, $data, $where) {
return $this->db->update($table_name, $data, $where);
}
public function get_data_by_join($table, $table2, $where, $table1_column, $table2_column, $limit = '', $order_column = '', $order_by = 'DESC', $select_columns = '', $is_single_record = false, $group_by = '', $join_by = '', $offset = '') {
if (!empty($select_columns)) {
$this->db->select($select_columns);
} else {
$this->db->select('*');
}
$this->db->from($table);
$this->db->join($table2, $table . '.' . $table1_column . '=' . $table2 . '.' . $table2_column, $join_by);
$this->db->where($where);
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
} else {
$this->db->limit($limit);
}
}
if (!empty($order_column)) {
$this->db->order_by($order_column, $order_by);
}
if (!empty($group_by)) {
$this->db->group_by($group_by);
}
$query = $this->db->get();
if ($query->num_rows() > 0) {
if ($is_single_record) {
$rs = $query->result_array();
return $rs[0];
} else {
return $query->result_array();
}
} else {
return false;
}
}
function DeleteRecord($table_name, $where) {
return $this->db->delete($table_name, $where);
}
function managerecord() {
$count = 1;
$where = array('channel_id' => 8,
'field_id_12 !=' => '');
$this->db->where($where);
$query = $this->db->get('channel_data');
$data = $query->result_array();
foreach ($data as $value) {
$id = $value['field_id_12'];
$update = array('telephone' => $value['field_id_53'],
'about' => $value['field_id_54'],
'license' => $value['field_id_18'],
'broker' => $value['field_id_19'],
'preferred' => 'yes');
$this->db->update('members', $update, array('member_id' => $id));
}
echo "done1";
}
public function get_content_landing_page($table = false, $field = false, $id = false, $id_name = false) {
$this->db->select($field);
$this->db->from($table);
$this->db->where($id_name, $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_field_landing_page($id = false,$fields=false) {
$this->db->select($fields);
$this->db->from('terratino_form_fields_master');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
?>

Resources