ksharifi's avatar

Pagination Issue

Hello Guys,

I'm wondering for a wierd issue while using laravel pagination.

i wrote this code block:

Route::get('products/{categoryId?}', function($categoryId = null) {
    if($categoryId) {
        $products = \App\Product::where('active', 'y')
            ->where('category_id', $categoryId)
        ->paginate(12);
    } else {
        $products = \App\Product::where('active', '=', 'y')->paginate(12);
    }
    return view('frontend.pages.products', ['products' => $products]);
});

And its working, but this one:

Route::get('products/{categoryId?}', function($categoryId = null) {
    $products = \App\Product::where('active', 'y');
    ($categoryId) AND $products->where('category_id', $categoryId);
    $products->paginate(12);
    return view('frontend.pages.products', ['products' => $products]);
});

Not working and i get: Call to undefined method Illuminate\Database\Query\Builder::render() Error. Here is my view:

{!! $products->render() !!}
0 likes
5 replies
bobbybouwmann's avatar

This doesn't seem to look right to me...

$products = \App\Product::where('active', 'y');
($categoryId) AND $products->where('category_id', $categoryId);
$products->paginate(12);

You can update it to this, and it should work fine ;)

$products = \App\Product::where('active', 'y');

if ($categoryId) {
    $products->where('category_id', $categoryId);
}

$products->paginate(12);
1 like
veve286's avatar
veve286
Best Answer
Level 8

try this .

   

if ($categoryId) {
    $products->where('category_id', $categoryId);
}
$paginated_data=$products->paginate(12); // here you forget to assign your results to variable
 return view('frontend.pages.products', ['products' => $paginated_data]);

1 like
veve286's avatar

You can use where( ),orWhere( ) , skip( ), take ( ) methods to chain like this without having to assign to the variable.

So you can do like this.


$products = \App\Product::where('active', 'y');
$products->skip(5); 
// this skip method effects to the $products object and assign filter result to the $products object
$products->take(10);
 // this take method effects to the $products object and assign filter result to the $products object
$products->orWhere('foo',bar);
// this orWhere method effects to the $products object and assign filter result to the $products object

Here is your problems come

//This all  effect to the $products query object but not assign results to the $products 
//$products can only store query object not collection results object
//So you need variable to accept the results from the following methods
$products->get( );
$products->paginate(10 );
$products->first( );
$products->lists('id');

Sorry for my bad english

Please or to participate in this conversation.