0

I'm facing a weird problem which only happen in the production server (It's 100% normal in my local). I'm using Laravel 8, and have a model named Student. Inside the model, I created several scope methods like this:

public function scopeWhereAlreadySubmitData($query)
{
    return $query->where('status_data_id', '!=', 1);
}

public function scopeWhereAlreadySubmitDocument($query)
{
    return $query->where('status_document_id', '!=', 1);
}

Then I use the methods above in an AJAX controller to chain it with count method. Something like:

public function getAggregates()
{
    $student = Student::with(['something', 'somethingElse']);
    $count_student_already_submit_data = $student->whereAlreadySubmitData()->count();
    $count_student_already_submit_document = $student->whereAlreadySubmitDocument()->count();

    return compact('count_student_already_submit_data', 'count_student_already_submit_document');
}

Here's is where the weird thing happens: while the controller above produce the correct value in my local, in production count_student_already_submit_data has a correct value but count_student_already_submit_document has zero value. Seeing at the database directly, count_student_already_submit_document should have value more than zero as there are many records has status_document_id not equals to 1.

I've also tried to use the scopeWhereAlreadySubmitDocument method in tinker. Both in local and production, it shows the correct value, not just zero.

Another thing to note is that Student model actually had 4 scope methods like the above, not just 2. 3 of them is working correctly, and only 1 is not. Plus, there's another controller using all the scope methods above and all of them are showing the correct value.

Have you ever face such thing? What could be the problem behind this? Your input is appreciated.

rifqy abdl
  • 156
  • 1
  • 8

1 Answers1

0

Turns out this is because the query builder is effected by the given chain. The weird thing I mentioned about "local vs production" is likely doesn't gets noticed in the local because its only has a few records. I should've use clone() when chaining the builder. See the topic below for more information.

Laravel query builder - re-use query with amended where statement

rifqy abdl
  • 156
  • 1
  • 8