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

Badong's avatar

Query the first record of the relationship

Hello,

Good day, just want to ask if this is possible?

public function journals(){
    return $this->belongsToMany(Traders::class);
}

// Is there a way how to do this? 

$traders = Trader::whereHas('journals',function($q){
    $q->first()->where('query here');
});

I just want to query the first record of the relationship. Is that possible with eloquent? DB query is really not an option in our provided data.

Thank you in advance.

0 likes
1 reply
Vilfago's avatar

Not sure, but you can try:

$traders = Trader::with(['journals' => function($q){
    $q->first()->where('query here');
}]);
//or
$traders = Trader::with(['journals' => function($q){
    $q->where('query here')->first();
}])->get();

Please or to participate in this conversation.