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

MoFish's avatar

Simple Eloquent Query

Hi,

The below query works, but it's two queries instead of being one.

Could anyone help me tidy this query up please?

$page = Page::select('id')->where('uri', Request::segment(1))->first(); 
$section = PageSection::select('content')->where('name', $name)->where('page_id', $page->id)->first();

I have created a relationship in my Page model which hasMany PageSections, but unsure how best to perform the above query using it.

$page = Page::select('id')->where('uri', Request::segment(1))->with('pageSections')->first();
public function pageSections(){
    return $this->hasMany('App\PageSection');
}
0 likes
2 replies
Vilfago's avatar
Vilfago
Best Answer
Level 20

Your query seems good, but you will always have two queries launched in the background in using with.

If you really want one query, don't use with() but use join from the QueryBuilder.

Please or to participate in this conversation.