laravel 4 paginate collection

后端 未结 3 1584
天涯浪人
天涯浪人 2021-01-06 14:30

I cant create a proper pagination system using laravel 4. I have the following models and function that return collections:

Model Restaurant:

public          


        
相关标签:
3条回答
  • 2021-01-06 14:35

    I created a subclass of Collection and implemented my own paginate method

    public function paginate($perPage) {
        $pagination = App::make('paginator');
        $count = $this->count();
        $page = $pagination->getCurrentPage($count);
        $items = $this->slice(($page - 1) * $perPage, $perPage)->all();
        $pagination = $pagination->make($items, $count, $perPage);
        return $pagination;
    }
    
    0 讨论(0)
  • 2021-01-06 14:39

    The Laravel paginator does not do any of the splicing for you. Typically the paginator should be used hand in hand with Eloquent/Fluent. In your second example you should be doing it like this.

    return Restaurant::find($id)->fooditem()->paginate(5);
    

    Without calling the actual method you'll just be getting a collection of results and not the query builder instance.

    If you want to use the paginator manually you need to pass in the spliced array (the correct items for the current page). This usually involves determining the current page, the total results and total pages. That's why, where possibly, it's best to use it with Eloquent or Fluent.

    0 讨论(0)
  • 2021-01-06 14:49

    The paginator must get the items that it would normally get from a database query with an offset/limit statement. So when you have a collection with all items, you should do the offset/limit yourself.

        $food = $food->get_rest_foods($id);
    
        $page = 1;
        if( !empty(Input::get['page']) ) {
            $page = Input::get['page'];
        }
    
        $perPage = 15;
        $offset = (($page - 1) * $perPage);
    
        $food = Paginator::make($food->slice($offset,$perPage, true)->all(), $food->count(), $perPage);
    
    0 讨论(0)
提交回复
热议问题