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

simon_eds's avatar

Many-to-many query help required!

I have 4 models with the relevant migrations / tables: -topics -question_topic -questions -responses

Topics and questions are linked via the intermediate questions_topic table in a many-to-many relationship.

Questions are related to responses in a one-to-many relationship.

I need to be able to show a random selection of x questions for a specific topic and the related responses. I am however struggling to write the correct eloquent query.

I can get all the questions for a specific topic:

$questions = Topic::where('id',1)->with('questions')->get();

I can randomly get 10 questions and related responses, but not using topic to group as I need to:

$questions = Question::with('responses')->inRandomOrder()->limit(10)->get();

If I do something like this, the limit only applies to the topic, so I get all of the questions and responses for the specified topic. The random order would also not work here.

$questions = Topic::with('questions.responses')->where('id', 1)->limit(1)->get();

Any pointers as to how I should best proceed would be much appreciated!

0 likes
4 replies
simon_eds's avatar

Thank you very much for this - I am trying to use the method that doesn't use an intermediate model if possible. This is almost perfect:

Topic::find(1)->questions()->with('responses')->inRandomOrder()->limit(1)->get();

In this instance, the questions are randomised, but the responses are not. Each question has five potential responses.

Can I randomise these responses in the same eloquent query? I know I can do some array shuffle on the front-end, but I am trying to avoid that if possible.

If I can only achieve this with an intermediate model, then would also be fine.

I really appreciate your feedback.

andyabihaidar's avatar
Level 3

Create a new relationship in your questions model:

public function randomizedResponses() {
	return $this->hasMany(Response::class)->inRandomOrder();
}

and then use it in the with function instead of responses.

1 like
simon_eds's avatar

Awesome, thank you! I love how simple this is, but I still managed to miss it... I am still learning what can be achieved via eloquent vs. through the model relationships. This really helps.

Please or to participate in this conversation.