Zolax
Zolax

Reputation: 91

How to make Laravel 4 pagination

Hello everyone I'm trying to make pagination in Laravel 4 but my code doesn't work. I have controller with action:

public function getSingleProduct($prodName, $id)
    {               
        $singleProduct = Product::getOne($id);
        $getAllReviews = Review::getAllBelongsToProduct($id);
        $this->layout->content = View::make('products.single')
                                     ->with('reviews', $getAllReviews)
                                     ->with('products', $singleProduct);
    }

and I want to paginate getAllReviews (5 per page). I tried like this: $getAllReviews = Review::getAllBelongsToProduct($id)->paginate(5); but it doesn't work for me. Here is also my Review model

public static function getAllBelongsToProduct($id) {
     return self::where('product_id', '=', $id)
                ->join('products', 'reviews.product_id', '=', 'products.id')                    
                ->select('reviews.*', 'products.photo')
                ->orderBy('created_at', 'desc')
                ->get();
}

Where I have a mistake?

Upvotes: 0

Views: 698

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

Instead of that static method on your model use query scope, this will be flexible:

// Review model
public function scopeForProduct($query, $id)
{
    $query->where('product_id', $id);
}

public function scopeWithProductPhoto($query)
{
    $query->join('products', 'reviews.product_id', '=', 'products.id')                    
      ->select('reviews.*', 'products.photo');
}

Then use it:

// get all
$reviews = Review::forProduct($id)->withProductPhoto()->latest()->get();

// get paginated
$reviews = Review::forProduct($id)->withProductPhoto()->latest()->paginate(5);

latest is built-in method for orderBy('created_at', 'desc').

If you want to have just a single call in your controller, then chain the above and wrap it in methods on your model.

Upvotes: 1

Related Questions