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

haakym's avatar

Assign a query to variable to then perform two separate queries?

Hey everyone, just wondering if I can start an eloquent query, assign it to a variable then continue using the variable for two separate queries without them conflicting with one another. A simple example:

$students = $this->student
    // more query stuff
    ->where('is_active', 1);

$bachelorStudents = $students
    ->where('course_id', 3)
    ->get();

$masterStudents = $students
    ->where('course_id', 4)
    ->get();

or would I need to do:

$bachelorStudents = $this->student
    ->where('course_id', 3)
    ->get();

$masterStudents = $this->student
    ->where('course_id', 4)
    ->get();

I always thought I could do the former, but some of my results appear to show I can't but I am open to believe that if you can do it then perhaps I'm doing something wrong.

0 likes
5 replies
screenager's avatar
$queryStudent = Student::whereIsActive(1);
$bachelorStudents = $queryStudent->whereCourseId(3)->get();
$masterStudents = $queryStudent->whereCourseId(4)->get();
haakym's avatar

@screenager I don't see how that answers the question? All you've done is modify the syntax of the code snippet I put in my question. Please clarify further if you can.

screenager's avatar

It's better syntax (shorter, perhaps more verbose) and also makes more sense then writing something like

$students = $this->student

However, if by that line you mean you want to work on an existing relation that returns a collection, I suggest you work with "filters"

$bachelorStudents = $students->filter(function(Student $student) {
  return $student->course_id == 3;
});
$masterStudents = $students->filter(function(Student $student) {
  return $student->course_id == 4;
});

If I still don't get it, perhaps you should reformulate your question

haakym's avatar

@screenager Again, I don't see how your code with altered syntax addresses the question. Thanks for your comment anyway though, it's always good to get a different perspective.

Yes, you're right I think I can use filters as one approach, thanks a lot.

As for the question I asked: can I start an eloquent query, assign it to a variable then continue using the variable for two separate queries without them conflicting with one another, the feedback I got from stackoverflow was no I can't, so use query scopes or I could use filters as you suggested.

http://stackoverflow.com/questions/34131581/assign-a-query-to-variable-to-then-perform-two-separate-queries#34131892

Please or to participate in this conversation.