Support the ongoing development of Laravel.io →
Database Eloquent

I have a User and a Trip model with belongsToMany relationships and a pivot table between. I'm trying to get Trips that have been modified since the User joined (ie since the trip_user record was created). In the Trip model I have the following scope:

public function scopeModified($query) {
    return $query->where('trip_user.created_at', '<', 'trips.updated_at');
}

This is how it's called ($user is the current user):

return $user->trips()->modified()->get();

This always returns all of the User's Trips.

What's strange is that when I log the query with DB::getQueryLog(), it spits out the exact right query:

select `trips`.*, `trip_user`.`user_id` as `pivot_user_id`, `trip_user`.`trip_id` as `pivot_trip_id`, `trip_user`.`created_at` as `pivot_created_at`, `trip_user`.`updated_at` as `pivot_updated_at` 
from `trips` 
	inner join `trip_user` on `trips`.`id` = `trip_user`.`trip_id` 
where `trip_user`.`user_id` = ?
and `trip_user`.`created_at` < ?

with the bindings ["3","trips.updated_at"]

if I copy this query and run it directly in MySQL, I get the results I want. But running return $user->trips()->modified()->get(); always returns all the trips.

Any thoughts would be appreciated. I know this is a tough one to describe or replicate without the rest of the code.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.