Eloquent - multiple 'when' conditions in query - laravel

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.

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!

Filter by date range OR member ID

I am trying to filter the data either by date range or by member ID. Below is what I have tried but it returns page not found.
I been tried many ways but still can't display out the data. The route url to blade is all correct however it just not displaying the blade file. It is something wrong in my controller codes?
Controller
$members = Membership::with(['profile'])
->when($request->memberId, function ($query) use ($request) {
$query->where('id', 'LIKE', '%' . $request->value . '%');
})
->when($request->dateStarted, function ($query) use ($request) {
$dateS = date('Y-m-d', strtotime($request->dateStarted));
$query->whereDate('created_at', '>=', $dateS);
})
->when($request->dateEnded, function ($query) use ($request) {
$dateE = date('Y-m-d', strtotime($request->dateEnded));
$query->whereDate('created_at', '<=', $dateE);
})
->latest()
->paginate(15);
Route
Route::get('/members-listing', [$ControllerClass, 'memberListing'])->('members-listing');
and below is the script to call the api through route url
<script>
function generate() {
var route = '{{ route('members-listing') }}';
var filterBy = $('select[name="filter-by"]').val();
var memberId = $('input[name="member-id"]').val();
var dateStarted = $('input[name="date-started"]').val();
var dateEnded = $('input[name="date-ended"]').val();
if (filterBy != null && filterBy == "filter-lead-id") {
route = route + '&filterBy=' + filterBy + '&leadId=' + leadId;
} else if (filterBy != null && filterBy == "filter-date") {
route = route + '&filterBy=' + filterBy + '?dateStarted=' + dateStarted + '&dateEnded=' + dateEnded;
}
window.location.href = route;
}
$(document).ready(function() {
$("#filter-date").hide();
$('#filter-by').change(function() {
$('.filter').hide();
$('#' + $(this).val()).show();
});
});
</script>
$query = Membership::with(['profile']);
if(isset($request->memberId) && !empty($request->memberId))
{
$query->where('id', 'LIKE', '%' . $request->value . '%');
}
if(isset($request->dateStarted) && !empty($request->dateStarted))
{
$dateS = date('Y-m-d', strtotime($request->dateStarted));
$query->whereDate('created_at', '>=', $dateS);
}
if(isset($request->dateEnded) && !empty($request->dateEnded))
{
$dateE = date('Y-m-d', strtotime($request->dateEnded));
$query->whereDate('created_at', '<=', $dateE);
}
$query->latest()->paginate(15);

Where function query withcount not working Laravel

this works perfectly fine
return Webinar::query()
->withCount('users')->orderByDesc('users_count')
->get();
but I need to use a condition for sorting, but this doesnt work
return Webinar::query()
->where(function($query) use ($sort_by) {
if($sort_by == 0) {
return $query->withCount('users')->orderByDesc('users_count');
} else {
return $query->withCount('review')->orderByDesc('review_count');
}
})
->get();
I also tried a condition inside like this to check my if else function
return Webinar::query()
->where(function($query) use ($sort_by) {
if($sort_by == 0) {
return $query->withCount('users')->orderByDesc('users_count')
->where('status', 2);
} else {
return $query->withCount('review')->orderByDesc('review_count')
->where('status', 1);
}
})
->get();
but the where status is only working not withcount. I hope someone can answer, thank you so much
How about you move condition code outside query
but I need to use a condition for sorting, but this doesnt work
if ($sort_by === 0) {
$order = 'users_count';
$count = 'users';
} else {
$order = 'review_count';
$count = 'review';
}
return Webinar::query()
->withCount('users')->orderByDesc($order)
->get();

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

Laravel search with multiple conditions

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?

Resources