Conditional search in relations
$search = 'Ford'
$set = CarModel::with(
'brand_info',
'country_info',
'color_info',
'engine_info',
'cuser',
'muser'
)
->whereHas('color_info', function ($q) {
$q->where('color', '=', 'red'); // only red cars
})
->where('active', '=', 1);
if ($search !== false && $search !== '') {
$set->where(function ($query) use ($search) {
// where on the parent model
$query->where('name', 'LIKE', "%{$search}%");
// other columns to be searched in the parent model
$columns = ['description', 'notes'];
foreach ($columns as $column) {
$query->orWhere($column, 'LIKE', "%{$search}%");
}
// also include the search in the country info
$query->orWhereHas('country_info', function ($q) use ($search) {
$q->where(function ($q) use ($search) {
$q->where('name', 'LIKE', "%{$search}%");
});
});
// and also in the engine_info relation engine_parts (one level deeper)
$query->orWhereHas('engine_info.engine_parts_info', function ($q) use ($search) {
$q->where(function ($q) use ($search) {
// part_no is in the engine_parts relation within the engine model.
$q->where('part_no', 'LIKE', "%{$search}%");
});
});
});
}
// total of all finds (no start, limit yet)
$this->total = $set->count();
// here we get the records we need (with start, limit)
$this->results = $set->orderby('number')
->limit($limit)
->offset($start)
->get();
// count of the records in this set
$this->count = $set->count();
Last update: Tue, 13 Sep 2022 14:32:15