Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JABirchall's avatar

Constrain a with condition by the parent query

So i have a query to get a route someone has taken and where they vitisted

Route::with([
		'streets',
		'streets.identifiable' //Polymorphic relationship
		'streets.identifiable.visits' // <- this is fetching all visits
])->where('status', 'complete')
->where('user_id', '12')
->get();

The problem im having is the street.identifiable.visit relationship is fetching all the visits. I want to constrain it to the parent Route. The visits table has a route_id and I want to constrain it to the Route row, ive tried

'streets.identifiable.visits' => fn(BelongsToMany $query) => $query->where('visits.route_id', 'routes.id');

But that just ends up with error.

0 likes
3 replies
Sinnbeck's avatar

To compare columns you use whereColumn()

JABirchall's avatar

@Sinnbeck that doesnt work because routes.id doesnt exist in the visits query.

ATM its only selecting where in the visits are for an identifiable.id, But i always want to add a where for visits for the visit.route_id = route.id

JABirchall's avatar
JABirchall
OP
Best Answer
Level 16

Update, I fixed it by moving that 1 nested relationship into a load. and using the fetched modal to query against.

$route->load([
	'streets.identifiable.visits' => fn($query) => $query->where('route_id', $route->id);
]);

Please or to participate in this conversation.