0
My Controller method is:

$topics=Topic::with(array('subtopics'=>function($query){
            $query->orderBy('glc_subtopic_priority','asc');
        }))->with('subtopics.resources')->find($id)->paginate(1);
        return View::make('subtopics.index')->with('topics', $topics);

I am eager loading this and it works fine. But now I want to paginate this. I have tried {{ dd($topics->toArray()) }} and it returns me this:

array (size=7)
  'total' => int 2
  'per_page' => int 1
  'current_page' => int 1
  'last_page' => int 2
  'from' => int 1
  'to' => int 1
  'data' => 
    array (size=1)
      0 => 
        array (size=5)
          'id' => int 1
...........

The problem is when I am displaying the data. I am using

@foreach($topics->subtopics as $topic)
    <li>{{ $topics->glc_subtopic_name }}</li>
        {{ $topic->glc_subtopic_content }}
        @foreach($topic->resources as $resource)
        <br/>{{ $resource->glc_subtopic_resource_url }}
    @endforeach
@endforeach

This returns me the error: Undefined property: Illuminate\Pagination\Paginator::$subtopics

How should I access the data in the paginated variable $topics.

dabadaba
  • 9,064
  • 21
  • 85
  • 155
Sonali Gupta
  • 288
  • 1
  • 5
  • 17

1 Answers1

0

If you need to specify the query for subtopics, you should eager load your resources models from within that query rather than eager loading subtopics again.

Try this:

$topics = Topic::with(['subtopics' => function($query){
    $query->with('resources')->orderBy('glc_subtopic_priority','asc');
}])->find($id)->paginate(1);

return View::make('subtopics.index', ['topics' => $topics]);
c-griffin
  • 2,938
  • 1
  • 18
  • 25
  • I did this. I want to paginate the subtopics and not the topics. For that I put paginate function inside: Topic::with(['subtopics' => function($query){ $query->with('resources')->orderBy('glc_subtopic_priority','asc')->paginate(1); }])->find($id); I am not able to access $topics->links() now. Is there any way of doing this? – Sonali Gupta Sep 09 '14 at 18:08
  • Hhmmm, i haven't tried anything like this, but `links()` would be a method of the relationship that is paginated. So, possibly `$topics->subtopics->links()`, but since you're only looking for 1 specific topic, why not just query your subtopics directly and pass it to your view? `$subtopics = Subtopic::with('resources')->orderBy('glc_subtopic_priority','sac')->where('topic_id', $id)->paginate(10)` / `return View::make('subtopics.index', ['subtopics' => $subtopics]);`/ `{{ $subtopics->links() }}` – c-griffin Sep 09 '14 at 21:01
  • I tried with $topics->subtopics->links(). But $topics->subtopics is a collection. I did the other way you proposed. It works now! Thank you!! – Sonali Gupta Sep 10 '14 at 14:51