Search code examples
phplaravellaravel-4fluentlaravel-blade

Laravel: paginating a fluent query


I'm trying to paginate a page in my view like this:

@foreach($tasks as $task)
    {{ $task->user_id }}
    {{ $task->client_id }}
    {{ $task->description }}
    {{ $task->duration }}
    {{ link_to_route('clients.show', 'View client', array($task->client_id), array('class' => 'btn btn-primary')) }}
@endforeach
    {{ $tasks->links() }}

Using the following query in my controller:

$tasks = DB::table('tasks')
    ->join('users', 'tasks.user_id', '=', 'users.id')
    ->join('clients', 'tasks.client_id', '=', 'clients.id')
    ->select(array('tasks.description', 'tasks.duration', 'tasks.client_id', 'tasks.user_id', 'users.email', 'clients.name'))
    ->where('tasks.group_id', '=', $usergroup)
    ->orderBy('tasks.created_at', 'DESC')
    ->paginate(20);

    return View::make('tasks.index', compact('tasks'));

It shows the tasks fine but there's no pagination link showing up so I can't head over to the next batch of 20 results.

Any ideas on how I can make this work?

I've tried @foreach($tasks->result as $task) in my view as suggested in http://forums.laravel.io/viewtopic.php?id=4092 but it gives me an error "Undefined property: Illuminate\Pagination\Paginator::$result"


Solution

  • For those playing at home - I discovered the answer to this:

    The compact function is converting the object to an array. Change your return view method to:

    return View::make('tasks.index')->with('tasks', $tasks);
    

    And you're in the clear!

    Another point - if you're using Bootstrap 3 RC1 like me you'll find that pagination breaks because of the way BS3 styles pagination - if you have that issue head over here for the solution: https://github.com/laravel/laravel/issues/2215

    :)