AtomCoder's avatar

Relationship Pagination Error

Hi Guys,

Having issue trying to paginate a "Product / Comments" relationship.

Using the query below, its works in terms of paginating, only 4 results are displayed as expected.

However when I use {{ $product->comments->links() }} with the blade file I get the following error:

Method Illuminate\Database\Eloquent\Collection::links does not exist.

Any ideas why the pagination links are not rendering ?

$product = Product::with([
    'photos',
    'county',
    'town',
    'watchers',
    'comments' => function ($query) {
            $query->select('*')->with([
                'user' => function ($query) {
                    $query->select('id', 'name', 'email');
                } 
            ])->paginate(4);
        },
    'category',
    'sub_category',
    'can_message',
    'seller' => function ($query) {
            $query->select('id', 'name');
        } 
    ])
    ->where('id', $request->id)->where('status', 'live')
    ->orWhere('status', 'sold')
    ->first();

	etc.........

	return view('products.product')->with(compact('product'));
0 likes
4 replies
JeffH's avatar

I'm pretty sure you can't call paginate in the relationship query. I think you will need to fetch it separately.

$comments = $product->comments()->paginate(4);
1 like
AtomCoder's avatar

@JeffH But the thing is, I am calling it within the query and I'm getting the expected result. I just cant access the pagination links in blade.

MohamedTammam's avatar
Level 51

As @jeffh mentioned, you can't call paginate inside the relationship query, if you're going to fetch only one Product I suppose your code to look like

$product = Product::with([
    'photos',
    'county',
    'town',
    'watchers',
    'category',
    'sub_category',
    'can_message',
    'seller' => function ($query) {
            $query->select('id', 'name');
        } 
    ])
    ->where('id', $request->id)->where('status', 'live')
    ->orWhere('status', 'sold')
    ->first();

$comments = $product->comments()->with([
                'user' => function ($query) {
                    $query->select('id', 'name', 'email');
                } 
            ])->paginate(4);
1 like

Please or to participate in this conversation.