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

simioluwatomi's avatar

Query builder help

Ministry model

public function messages()
    {
        return $this->hasMany(Message::class);
    }

public function series()
    {
        return $this->hasMany(Series::class);
    }

public function profile()
    {
        return $this->hasOne(Profile::class);
    }

I have this method that fetches all messages. The issue is that I want the result to also return the profiles of the ministry. What I'm I missing?

public function indexmessages()
    {
        return Message::with('ministry', 'preacher', 'series')->get();
    }

Also, I have this N + 1 problem with a method

public function showseries(Series $series)
    {
        return [$series, $series->messages];
    }

This query returns the series, and the messages in the series but performs an extra query.

0 likes
4 replies
IgorBabko's avatar
Level 36

Hey -

Try it like this -

public function indexmessages()
{
    return Message::with('ministry.profile', 'preacher', 'series')->get();
}

The code below executes exactly 2 queries, that's how eloquent works. When laravel injects $series into this method - that will be one query, and when you write $series->messages - that will be the second query.

public function showseries(Series $series)
{
    return [$series, $series->messages];
}
simioluwatomi's avatar

Ok. Now I understand. But how should the code now be written? I meant this

public function showseries(Series $series)
{
    return [$series, $series->messages];
}

Because I already have a relationship set up in my series model like so

public function messages()
    {
        return $this->hasMany(Message::class);
    }
IgorBabko's avatar

@simioluwatomi I would go with this approach -

public function show(Series $series)
{
    return $series->load('messages');
}
1 like

Please or to participate in this conversation.