To address your issue, you need to ensure that your query logic correctly prioritizes pages with a matching related site ID over pages without any related sites. The current query returns both types of pages because it uses an or condition that doesn't enforce exclusivity.
To achieve the desired behavior, you can use a more refined approach by first attempting to find a page with a matching related site ID. If no such page exists, then you can fall back to finding a page without any related sites.
Here's a solution that should work for your case:
$site = app(Site::class); // set during middleware
// First, try to find a page with a matching related site ID
$errorPage = Page::where('type', '404')
->whereHas('sites', function (Builder $query) use ($site) {
$query->where('id', $site->id);
})
->first();
// If no such page exists, find a page without any related sites
if (!$errorPage) {
$errorPage = Page::where('type', '404')
->doesntHave('sites')
->first();
}
This code first attempts to find a 404 page that has a related site with the given site ID. If such a page is found, it is returned. If not, the code then looks for a 404 page that does not have any related sites.
This approach ensures that you only get one page, either the one with the matching related site ID or the one without any related sites, depending on availability.