Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent pagination on relationships

I am trying to paginate a Eloquent relationship like this:

 $query = Product::find(1)->options()->paginate();

But I get the following error:

Fatal error: Call to a member function getCurrentPage() on a non-object

I have confirmed that the code $query = Product::find(1)->options() returns a collection of options. The $query object seems to be of type hasMany. Below are the model classes I am using.

class Product extends Eloquent
{

    protected $table = 'products';

    public function options ()
    {
        return $this->hasMany('ProductOption', 'product_id');
    }
}

class ProductOption extends Eloquent
{
    protected $table = 'product_options';

    public function product()
    {
        return $this->belongsTo('Product', 'product_id');
    }
}

Does eloquent not return paginated results for relationships?

like image 649
Jen Zhang Avatar asked Aug 26 '14 03:08

Jen Zhang


People also ask

How can I get pagination in Laravel?

There are several ways to paginate items. The simplest is by using the paginate method on the query builder or an Eloquent query. The paginate method provided by Laravel automatically takes care of setting the proper limit and offset based on the current page being viewed by the user.

How can we manually create pagination in Laravel?

Creating A Paginator Manually Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator instance, depending on your needs.

How does pagination work in Laravel?

Pagination works by selecting a specific chunk of results from the database to display to the user. The total number of results is calculated and then split between pages depending on how many results you want to return on a page.


1 Answers

You can not lazy load relational pagination like that, instead in your Product Model put the following function below your options has many relationship

public function getOptionsPaginatedAttribute()
{
    return $this->options()->paginate(10);
}

This will allow you to call the pagination on your relational data by

$product->options_paginated
like image 170
41eight Avatar answered Oct 22 '22 13:10

41eight