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

maxshy1337's avatar

Pass Model ID to Eloquent ->with(where("id",ID))

Hello everyone, how to pass ID of Group to Retrieve all Student journals where group_id equals to current group?

//    Group Model
    public function students(): BelongsToMany
    {
        return $this->belongsToMany(Student::class)
            ->select('id', 'city')
            ->with('user')
            ->without('groups', 'lessons', 'journals')
            ->with('journals',function($q) {
                $q->where('group_id', $this->id); //Not working, also tried $this->getKey()
				$q->where('group_id', 3); //For example group_id=3, Working
            });
    }
0 likes
1 reply
tykus's avatar

This is unnecessary:

->with('journals',function($q) {
    $q->where('group_id', $this->id); //Not working, also tried $this->getKey()
    $q->where('group_id', 3); //For example group_id=3, Working
});

the $q->where('group_id',... is implied (in the eager-loading query there will be a whereIn constraint based on the loaded Groups' id. It is enough to:

->with('journals')

Please or to participate in this conversation.