I have a table that has a polymorphic relation with 3 tables, maintenance_dealer, obsolescence_dealer, and Hospital_Equipment_Master. I want to search based on two tables only maintenance_dealer and obsolescence_dealer, but whenever I send a request it searches all tables and since some relationships are only defined in maintenance_dealer and obsolescence_dealer, and not on Hospital_Equipment_Master it throws an error.
Here is my code:
public function __invoke()
{
$searchParameters = request()->only([
'hospital_id',
'machinery_id',
'serialNo',
'issue_id',
'assigned_to',
]);
$query = Staff_Performances::with('staff.position', 'performance.stockSNW.hospitals', 'performance.stockSNW.machinery', 'performance.stockSNW.stockSerialMachineStatus.machineStatus', 'performance.issues', 'performance.master')
->where('performance_type', 'AppModelsHospitalsMaintenanceReportbio_md_maintenance_dealer')
->orWhere('performance_type', 'AppModelsHospitalsObsolescencesbio_md_obsolescence_dealer')
->orderByDesc('id');
// Apply search parameters
foreach ($searchParameters as $field => $value) {
if ($value !== null) {
if ($field === 'machinery_id') {
$query->whereHas('performance.stockSNW.machinery', function ($subQuery) use ($value) {
$subQuery->where('en_name', 'like', '%' . $value . '%');
});
}
elseif ($field === 'hospital_id') {
$query->whereHas('performance.stockSNW.hospitals', function ($subQuery) use ($value) {
$subQuery->where('id', $value);
});
} elseif ($field === 'serialNo') {
$query->whereHas('performance.stockSNW', function ($subQuery) use ($value) {
$subQuery->where('serialNo', 'like', '%' . $value . '%');
});
} elseif ($field === 'issue_id') {
$query->whereHas('performance.issues', function ($subQuery) use ($value) {
$subQuery->where('en_name', 'like', '%' . $value . '%');
});
} elseif ($field === 'assigned_to') {
$query->whereHas('staff.position', function ($subQuery) use ($value) {
$subQuery->where('en_title', 'like', '%' . $value . '%');
});
}
}
}
so stockSNW is only defined in maintenance_dealer and obsolescence_dealer and not in Hospital_Equipment_Master hence it throws this error:
"message": "Call to undefined method App\Models\Hospitals\Receipts\Hospital_Equipments_Master::stockSNW()",