Please help me to simplify Laravel eloquent query. Is there a way to make it more simple, please suggest because I have a couple of these in my code or suggest me any strategy to make it simpler?
if(! empty($has_due_date)) {
$resourceQuery->whereHas('stages', function ($query) use ($has_due_date) {
$query->whereHas('groups', function ($query) use ($has_due_date) {
$query->whereHas('tasks', function ($query) use ($has_due_date){
if ($has_duedate == 'yes'){
$query->whereNotNull('due_date');
}else if($has_duedate == 'no'){
$query->whereNull('due_date');
}
});
});
});
}
My Answer:
You can simplify the above query by using the `when` method in Laravel Eloquent. Here's how you can rewrite the query:
php
$resourceQuery->whereHas('stages.groups.tasks', function ($query) use ($has_due_date) {
$query->when($has_due_date == 'yes', function ($query) {
$query->whereNotNull('due_date');
})->when($has_due_date == 'no', function ($query) {
$query->whereNull('due_date');
});
});
This way, you can avoid nesting multiple `whereHas` functions and make the query more readable and maintainable.
Rate this post
4 of 5 based on 9889 votesComments