Search code examples
paginationlaraveleloquentlaravel-3

Trying to use laravel pagination breaks my controller/view


I'm trying to get Pagination working in Laravel. I've not used pagination before so am trying to use some examples from the docs and google results. I'm wondering if I need to turn 'pagination' on somewhere in config.

Here's my simple working controller:

public function get_index() {
  $locations = Location::all();
  return View::make('location.index')->with('locations', $locations)->render();
}

When I try and add pagination like this it breaks:

public function get_index() {
  $locations = Location::paginate(5);
  return View::make('location.index')->with('locations', $locations)->render();
}

..and I get the error:

Unhandled Exception

Message:
Error rendering view: [location.index]

Trying to get property of non-object

Here's my location.index view:

@layout('layouts.blank')
@section('content')
<div class="row">
<div class="twelve columns">
    <div role="main" id="content">
        <h3>Locations - All</h3>
        @if($locations)
            <table class="twelve">
                <thead>
                    <tr>
                        <th style="text-align: left;">Address</th>
                        <th>Area</th>
                        <th>Region</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                @foreach($locations as $location)
                <tbody> 
                    <tr>
                        <td style="text-align: left;">{{ $location->company,', ',$location->add_name,', ',$location->add_city }}</td>
                        <td> – </td>
                        <td> – </td>
                        <td>{{ HTML::link('location/update/'.$location->id, '',array('class'=>"foundicon-edit updateicon")) }}</td>
                        <td>{{ HTML::link('location/delete/'.$location->id, '',array('class'=>"foundicon-remove warnicon")) }}</td>
                    </tr>
                </tbody>
                @endforeach
            </table>
        @else
          Looks like we haven't added any locations, yet!
        @endif
        <p>{{ HTML::link('location/create', 'Create a location', array('class'=>"small radius button")) }}</p>
    </div>
</div>
</div>
@endsection

Solution

  • I hadn't read deeply enough into the subject. It's now working and here's what I had to change in the view:

    //from:
    @foreach($locations as $location)
    
    //to:
    @foreach($locations->results as $location)
    

    That returned just 5 results. Then to add links to the footer of my table I added this HTML/Blade:

    <tfoot>
      <tr>
        <td colspan="5"> {{ $locations->links() }} </td>
      </tr>
    </tfoot>
    

    Hope someone else benefits as I didn't find this terribly clear in the docs.