0

I have two data tables vehicles and trips, which have a one to many relationship and allow for multiple trips per vehicle. route is a column in the trips table. I want to see the vehicle list for a specific route, so I ran the following query.

$trips = Trip::with('vehicle')
     ->where('route', $route)
     ->get()->pluck('vehicle');

It work's fine, returns a vehicle collection. Now that I have the vehicle collection I want the active trip information with every vehicle model. I tried the following query.

$trips = Trip::with('vehicle', ['vehicle.activeTrip' => function ($query) {
            $query->where('status', 0);
        }])
        ->where('route', $route)
        ->get()->pluck('vehicle');

status = 0 indicates an active trip. But it is unsuccessful anyway. I got an error with the message Method name must be a string. Can anyone assist me in resolving my problem?

2
  • are trip and activeTrip actually different tables? Commented Nov 16, 2022 at 20:15
  • Actually same table but different relationship, for active trip I use one to one relationship. Commented Nov 16, 2022 at 20:22

2 Answers 2

2

Would you use this syntax


$trips = Trip::with(['vehicle','vehicle.activeTrip' => function ($query) {
            $query->where('status', 0);
        }])
        ->where('route', $route)
        ->get()->pluck('vehicle');
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, it's working, I made that silly mistake.
@ShahFoyez oh nice, please rate the answer :)
1

I just came across another solution. To retrieve the active trip data, we could use the Laravel ofMany method inside the Trip model.

public function activeTrip(){
return $this->hasOne(Trip::class, 'vid')->ofMany([], function ($query) {
    $query->where('status', 0);
});}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.