spAo's avatar
Level 1

Laravel pagination

hello i'm trying to do pagination to category page but its errors

web

 Route::get('/category/{slug}/{page?}', [WebController::class, 'category'])->name('category');

category model

 public function articles()
    {
        return $this->hasMany(Article::class, 'category_id', 'id')->orderBy('published_at', 'Desc');
    }

controller

public function category($slug, $page = 1)
    {
        $offsetPage = ($page - 1);
        $perPage = 24;
        $category = AllCategory::bySlug($slug);
        $category->articles->skip($perPage * $offsetPage)->take($perPage)->get();
        if (!$category) {
            abort(404);
        }
        return view('pages/category')
            ->with('category', $category);
    }

what i'm doing wrong?

0 likes
5 replies
spAo's avatar
Level 1

thanks for helping answer

automica's avatar

@spao why not use the built in method of pagination? https://laravel.com/docs/8.x/eloquent-resources#pagination

in your controller

public function category(Category $category) {

    $articles = $category->articles()->paginate(3);

    return view('articles.category', compact('category', 'articles'));
}

in your blade:

@foreach($articles as $article)
    // html
    @endforeach   

and add the following for your pagination links:

{!! $articles->links() !!}
2 likes

Please or to participate in this conversation.