How to add bracket in laravel query builder using 'WHEN' condition? - php

Given this code:
$objResellerList - DB::table('ResellerMaster as RM')
->leftJoin('StateMaster as SM','SM.id',RM.id_StateMaster')
->leftJoin('RegionMaster as REM','REM.id','=','RM.id_RegionMaster')
->leftJoin('DealerGroupMaster as DGM','DGM.id','=','RM.id_DealerGroupMaster')
->when($keywords, function($query) use ($keywords) {
return $query->where('RM.company_name', 'like', '%'.$keywords.'%')
->orWhere('DGM.name', 'like', '%'.$keywords.'%')
->orWhere('RM.email', 'like', '%'.$keywords.'%')
->orWhere('RM.pic', 'like', '%'.$keywords.'%')
->orWhere('RM.pic_mobile_no', 'like', '%'.$keywords.'%');
})
->when($status, function($query) use ($status) {
return $query->where('RM.status', $status);
})
->select('RM.*','SM.name as state','REM.name as region', 'DGM.name as dealer_group')
->orderby('RM.company_name','asc')
->paginate(10);
When i search with keywords, I need to close it with a bracket at when condition. How to include the bracket at when condition?

DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
give u brackets
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
so use where with function
->orWhere(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
or
->where(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
it will give u brackets
use
->when($status,function($query) {
return $query->where(function ($query) {
//do some action
})
})

Related

Coding laravel query [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
Improve this question
I'm trying to add a second searchterme that searches for number stars per users here are the table that I have
$searchTerm = $this->searchTerm;
$searchTermes1 = $this->searchTermes1;
$users = User::leftJoin('barbers', 'barbers.id_user', '=', 'users.id')
->whereHas('commandes', function ($query) use ($searchTermes1) {
$query->where('barbers.id', '>', 0)
->selectRaw('count(*) as count')
->havingRaw('count(*) >= ? or adress', [(int)$searchTermes1]);
})
->whereIn('barbers.id_state', [1, 4])
->where('isValidate', true)
->where(function ($query) use ($searchTerm) {
$query->where('barbers.name_barber', 'like', '%'.$searchTerm.'%')
->orWhereRaw("concat(first_name, ' ', last_name) like '%$searchTerm%'")
->orWhereRaw("concat(last_name, ' ', first_name) like '%$searchTerm%'");
})
->orderBy('barbers.created_at', 'desc')->paginate(10);
return view('livewire.barber-pagination', compact(['users']));
I tried this but it is not working
$users = User::leftJoin('avis', 'users.id', '=', 'avis.id_barber')
->leftJoin('barbers', 'barbers.id_user', '=', 'users.id')
->whereHas('commandes', function ($query) use ($searchTermes1,$searchTermes2) {
$query->where('barbers.id', '>', 0)
->havingRaw('count(*) >= ?', [(int)$searchTermes1]);
})
->whereIn('barbers.id_state', [1, 4])
->where('isValidate', true)
->where(function ($query) use ($searchTerm, $searchTermes3) {
$query->where('barbers.name_barber', 'like', '%'.$searchTerm.'%')
->orWhereRaw("concat(first_name, ' ', last_name) like '%$searchTerm%'")
->orWhereRaw("concat(last_name, ' ', first_name) like '%$searchTerm%'")
->havingRaw('sum(avis.rating) >= ?', [(int)$searchTermes3]);
})
->groupBy('users.id')
->orderBy('barbers.created_at', 'desc')
->paginate(10);
return view('livewire.barber-pagination', compact('users'));
I fixed the error but it returns just one result
$searchTerm = $this->searchTerm;
$searchTermes1 = $this->searchTermes1;
$searchTermes2 = $this->searchTermes2;
$users = User::leftJoin('barbers', 'barbers.id_user', '=', 'users.id')
->whereHas('commandes', function ($query) use ($searchTermes1) {
$query->where('barbers.id', '>', 0)
->havingRaw('count(*) >= ?', [(int)$searchTermes1]);
})
->where(function ($query) use ($searchTermes2) {
$query->whereHas('avis', function ($subquery) use ($searchTermes2) {
$subquery->havingRaw('avg(rating) >= ?', [(int)$searchTermes2]);
});
})
->whereIn('barbers.id_state', [1, 4])
->where('isValidate', true)
->where(function ($query) use ($searchTerm) {
$query->where('barbers.name_barber', 'like', '%'.$searchTerm.'%')
->orWhereRaw("concat(first_name, ' ', last_name) like '%$searchTerm%'")
->orWhereRaw("concat(last_name, ' ', first_name) like '%$searchTerm%'");
})
->orderBy('barbers.created_at', 'desc')
->paginate(10);

Laravel Where is getting ignored

My laravel "where" is getting ignored it seems. ->where('products.hide_product', '=', 'N')
Any ideas on what I am doing wrong?
$products = Product::join('brands','products.brand_id','=','brands.brand_id')
->join('categories','products.cat_id','=','categories.cat_id')
->leftJoin('images','products.product_id','=','images.product_id')->where('img_priority','=','1')->orWhere('img_priority', '=', null)
->where('products.hide_product', '=', 'N')->where('products.group_id', '=', $groupID)->orderBy('img_priority','DESC')
->get(array('products.en_71','products.astm','images.file_name','products.product_id','products.product_name','products.collect_part_no','brands.brand_name','categories.cat_name','products.status','images.file_type','products.pop','products.color_label','products.ai_complete'));
You can move the join in a closure an use the first where there:
$products = Product::join('brands', 'products.brand_id', '=', 'brands.brand_id')
->join('categories','products.cat_id','=','categories.cat_id')
->leftJoin('images', function ($join) {
$join->on('products.product_id','=','images.product_id')
->where('img_priority','=','1')
->orWhere('img_priority', '=', null);
})
->where(
['products.hide_product', '=', 'N'],
['products.group_id', '=', $groupID],
)
->select('products.en_71', 'products.astm', 'images.file_name', 'products.product_id', 'products.product_name', 'products.collect_part_no', 'brands.brand_name', 'categories.cat_name', 'products.status', 'images.file_type', 'images.img_priority', 'products.pop', 'products.color_label', 'products.ai_complete')
->orderBy('img_priority', 'DESC')
->get();
Please try below code.
$products = Product::join('brands','products.brand_id','=','brands.brand_id')
->join('categories','products.cat_id','=','categories.cat_id')
->leftJoin('images', function($join)) {
$join->on('products.product_id','=','images.product_id')
->where(function($query){
$query->where('img_priority','=','1')
->orWhere('img_priority', '=', null)
})
}
->where(function($query) {
$query->where('products.hide_product', '=', 'N')
->where('products.group_id', '=', $groupID)
})
->orderBy('img_priority','DESC')
->get(array('products.en_71','products.astm','images.file_name',
'products.product_id','products.product_name',
'products.collect_part_no', 'brands.brand_name',
'categories.cat_name', 'products.status',
'images.file_type','products.pop','products.color_label',
'products.ai_complete')
);

check condition within query in laravel

$q = Order::select(
'orders.*',
'items.date_start',
'items.date_end',
'items.location_name',
'items.category_id'
)
->join('items', 'items.item_id', '=', 'orders.item_id')
->leftJoin('orders_items', function ($join) use ($user_id)
{
$join->on('orders_items.order_id', '=', 'orders.order_id')
->on('orders_items.item_id', '=', 'orders.item_id')
->where('orders_items.user_id', '=', $user_id);
})
->with('Items')
->where(function ($query) use ($select_balance) { // This is where event is in the future, or it has a balance and is not draft.
$query->where('items.date_end', '>=', Carbon\Carbon::now()->toDateString())
->orWhere(function ($query) use ($select_balance) {
$query->where(DB::raw($select_balance), '>', 0)
->whereNotIn('orders.status', [0, 79]);
});
});
i would like to set a condition if (date_start == date_end) then
$query->where('items.date_end', '>=', Carbon\Carbon::now()->toDateString())
->orWhere(function ($query) use ($select_balance) {
$query->where(DB::raw($select_balance), '>', 0)
->whereNotIn('orders.status', [0, 79]);
});
else
$query->where('items.date_end', '>', Carbon\Carbon::now()->toDateString())
->orWhere(function ($query) use ($select_balance) {
$query->where(DB::raw($select_balance), '>', 0)
->whereNotIn('orders.status', [0, 79]);
});
how to set a condition within query i try to end query after ->with(items) but that say $q-> has syntax error please guide and explain how to over come this issue
You can use conditional clauses: https://laravel.com/docs/5.5/queries#conditional-clauses
Animals::when($condition, function($query) {
$query->where('size', 'big');
})->when(!$condition, function($query)) {
$query->where('size', 'small');
})->get();
In the example, if $condition is true then we fetch big animals, otherwise we fetch small animals.

How to handle And Where and Or Where conditions in Lumen?

I have this query:
SELECT * FROM users
WHERE
gender = "$gender" AND country = "$country"
AND ((city = "$city" AND status = "1")
OR (status IN(2,3)))";
How can I write above query in Lumen ?
What I have tried so far is :
$users = User::where('country', '=', $country)
->where('gender', '=', $gender)
->where(function ($users) {
$users->where('city', '=', '$city')
->where('status', '=', "1");
})
->whereIn('status', [2, 3])
->first();
But this query doesn't returns the expected result.
Any idea what is the fault in my query?
Try the following code.
$users = User::where('country', '=', $country)
->where('gender', '=', $gender)
->where(function ($query) use ($city) {
$query->where(function($query) use ($city) {
$query->where('city', '=', '$city')
->where('status', '=', "1");
})->orWhereIn('status', [2, 3]);
})->first();

Laravel 5 whereHas chaining and orWhere

Trying to query a model with a lower level relationship (agreement) and I cannot get chaining to work. I tried the three methods below (the second get me 99% of the way there, but it misses out on one of the results - an inactive equipment "status" and an "inactive" agreement (should have been omitted). What am I doing wrong?
Every piece of equipment needs to be "active" and have an active existing agreement (an active agreement is one that is either "Active", "Cancel on expiry" or "Unsigned").
$thing = Equipment::wherehas('agreement', function($q)use($month)
{
$q->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%')
->where('status', '=', 'Active')
->orWhere('status', '=', 'Unsigned')
->orWhere('status', '=', 'Cancel on expiry');
})->Get();
$thing = Equipment::wherehas('agreement', function($q)use($month)
{
$q->where('status', '=', 'Active')
->orWhere(function($q2)use($month)
{
$q2->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%');
})
->where('status', '=', 'Unsigned')
->orWhere(function($q3)use($month)
{
$q3->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%');
})
->where('status', '=', 'Cancel on expiry')
->orWhere(function($q4)use($month)
{
$q4->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%');
});
})->Get();
$thing = Equipment::wherehas('agreement', function($q)use($month)
{
$q->where('status', '=', 'Active')
->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%')
->orWhere('status', '=', 'Unsigned')
->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%')
->orWhere('status', '=', 'Cancel on expiry')
->where('equipment.status', '=', 'Active')
->where('maintenance_months', 'like', '%'.$month.'%');
})->get();
i am not quite understand why the where equipment.status is being filter for the same thing over and over again, if i am not understand wrongly the following code might be the result you are looking for.
$thing = Equipment::whereHas('agreement', function($q)use($month)
{
$q->where('maintenance_months', 'like', '%'.$month.'%')
->whereIn('status',['Unsigned','Active','Cancel on Expiry'])
})->where('status','Active')->get();

Categories