To filter the $members query to only include users with a currentAssignment where the station_id is equal to the value of $stationId, you can use the whereHas method. This method allows you to add query constraints to the relationships.
Here's how you can modify the $members query in your roster method:
public function roster($station, $shiftdate)
{
$stations = Station::where('status', 'published')->get();
$tstation = Station::where('status', 'published')
->where('code', $station)
->first();
if ($tstation) {
$stationId = $tstation->id;
// Use whereHas to filter users based on the currentAssignment relationship
$members = User::whereHas('currentAssignment', function ($query) use ($stationId) {
$query->where('station_id', $stationId)
->where('effective_dt', '<=', now())
->where(function ($query) {
$query->where('expiration_dt', '>', now())
->orWhereNull('expiration_dt');
});
})->with(['currentAssignment.rank', 'currentAssignment.title', 'currentAssignment.station', 'currentAssignment.shift'])->get();
} else {
// Handle the case where no matching station is found based on the provided $station code.
$members = collect(); // Return an empty collection or handle as needed
}
return view('companyops.roster', compact('stations', 'members', 'station', 'shiftdate'));
}
In this solution, the whereHas method is used to apply additional constraints to the currentAssignment relationship. It ensures that only users with a currentAssignment that matches the station_id and the date conditions are retrieved.
The use keyword is used to pass the $stationId variable into the closure so that it can be used in the query condition.
Remember to handle the case where $tstation is null appropriately, as in the provided code, it will return an empty collection. You might want to redirect the user or display a message indicating that the station was not found.