Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 4 paginate collection

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

Model Restaurant:

public function fooditem()
{
    return $this->hasMany('Fooditem','rest_id');
}
public function get_rest_foods($id){
    return Restaurant::find($id)->fooditem->toArray();
}

The second function returns all food items for a certain restaurant as an array. I also use this in an API call.

in my controller i have this:

 $food = $food->get_rest_foods($id);
 $paginator = Paginator::make($food, 10, 5);

I pass the paginator to the view and it shows the links ok but also shows all my item from the food array.

I tried using

public function get_rest_foods($id){
        return Restaurant::find($id)->fooditem->paginate(5);
    }

but i get an error:

FatalErrorException: Error: Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()

I searched this and many other sites but cant understant how to paginate a collection.

Thanks for your help

like image 341
user2137406 Avatar asked Nov 24 '25 14:11

user2137406


1 Answers

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);
like image 106
blablabla Avatar answered Nov 28 '25 01:11

blablabla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!