1

As I am now putting a lot of data in my database I needed to use laravel's paginate. However, it doesn't seem to work in my other query. Is there other way? or what did I do wrong?

My code is shown below

Paginate Working (ExamController)

$exams = Exam::with('users')->where('id',$userID)->paginate(5);

Paginate Not Working (Questions Controller)

$questions = Question::with(['exams','choices'])->where('exam_id', $examID)->paginate(5);

Code to display pagination

{{ $exams->links() }}   ---- exams view
{{ $questions->links()}}   ---- questions view

Error

Call to undefined method App\Question::links()

View

<div class="card">
  <div class="card-body">
    @foreach($questions as $index => $questions)
      {{$questions}}
    @endforeach
  </div>
  <div class="mt-3 d-flex justify-content-end text-right">
    {{$questions->links()}}
  </div>
</div>
Ralph
  • 193
  • 1
  • 4
  • 12
  • 1
    Are you going to get multiple `Exam` models with the same `exam_id`? `paginate()` doesn't do anything when it returns less records than the value passed to it (5 in this case). If you want to display the Questions for an exam and paginate those, you'd need to do something like `Question::where("exam_id", $examID)->paginate(5);` – Tim Lewis Mar 13 '19 at 16:28
  • Oh I see. But when I changed it to this way, when I `dd($questions);` it does return total of 6 and per page of 5. But when I display it on view it gives me error when I do `{{ $questions->links }}` but when I remove it, it still display 6 records. – Ralph Mar 13 '19 at 16:34
  • What does your `@foreach` loop look like? (I assume you're looping over them to display them?) – Tim Lewis Mar 13 '19 at 16:40
  • 5
    Yup knew it; you're overriding `$questions` in your loop. You can't do `@foreach($questions AS $questions)`, cause then `$questions` is no longer a Pagination object, it's a single `Question` model. See this answer: https://stackoverflow.com/questions/25247600/call-to-undefined-method-illuminate-database-query-builderlinks. To fix, just do `@foreach($questions AS $index => $question)`. (plural vs singular, variable naming is important) – Tim Lewis Mar 13 '19 at 16:45
  • Oh so it did was overriding the variable. I wasn't seeing this. Thank you so much @TimLewis! – Ralph Mar 13 '19 at 16:53
  • No problem; simple, generally harmless mistake. Happy to help though! – Tim Lewis Mar 13 '19 at 16:57

0 Answers0