@trukken I have a suggestion to use when() which will be a clean approach to me!
Check details: https://laravel-school.com/posts/laravel-code-refactoring-using-when-65/
Hey guys,
I am working on a filtering functionality, the filter is based on the query parameters coming from the URI. I have a load of parameters (17 to be precise), some of them match the exact column names on the Model I want to filter on.
However I have data that I have to access through intermediate tables and data that don't match the exact column names as well as date ranges.
How would you proceed?
My code looks like this as of right now.
foreach ($params as $field => $value) {
//Check if the field is a date range
if (str_ends_with($field, '_start')) {
$model->where(explode('_start', $field)[0], '>=', $value);
continue;
}
if (str_ends_with($field, '_end')) {
$model->where(explode('_end', $field)[0], '<=', $value);
continue;
}
//Check if the field is a relation
if (str_contains($field, '_id')) {
match ($field) {
'company_id' =>
$model->whereHas('companyHistory', function ($query) use ($value) {
$query->where('invoices.company_history_id', $value);
}),
'project_id' =>
$model->whereHas('projects', function ($query) use ($value) {
$query->whereIn('id', $value);
}),
'division_id' => $model->whereHas('division', function ($query) use ($value) {
$query->whereIn('id', $value);
}),
'user_id' => $model->whereHas('user', function ($query) use ($value) {
$query->whereIn('id', $value);
}),
'label_id' => $model->whereHas('labels', function ($query) use ($value) {
$query->whereIn('label_id', $value);
})
};
continue;
}
//If the value is an array, use whereIn
if (is_array($value)) {
$model->whereIn($field, $value);
continue;
}
$model->where($field, $value);
}
Please or to participate in this conversation.