You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Laravel集合分页问题:调用paginate方法提示不存在

Hey there! Let's work through this issue step by step.

Why the "Method paginate does not exist" error happens

Your original myWishlist() method calls get() at the end, which immediately executes the query and returns a Collection instance. The paginate() method belongs to Laravel's QueryBuilder—collections don't have this method, hence the error.

Fix the myWishlist() method to support pagination

Update your model method to return the query builder instead of executing the query right away. Remove the get() call:

// Wishlist model
public static function myWishlist()
{
    $userId = Auth::id();
    $bookIds = Wishlist::where('user_id', $userId)->pluck('book_id');
    
    // Return the query builder (no get() here!)
    return Book::whereIn('id', $bookIds);
}

Now this returns a query builder instance that you can chain paginate() onto in your controller.

Update your controller (small tweak included)

Your controller code mostly works, but fix the pagination offset calculation to match your 20-items-per-page setting:

public function index(Request $request)
{
    $books = Wishlist::myWishlist()->paginate(20);
    
    return view('wishlistCRUD.index', compact('books'))
        ->with('i', ($request->input('page', 1) - 1) * 20); // Changed 5 to 20 for accurate numbering
}

Display the paginated books in your view

In your wishlistCRUD.index blade view, loop through the $books collection to show each book, then add Laravel's built-in pagination links:

<!-- Render each book -->
@foreach($books as $book)
    <div class="book-card">
        <h4>{{ $book->title }}</h4>
        <p>By {{ $book->author }}</p>
        <!-- Add any other book details you need -->
    </div>
@endforeach

<!-- Render pagination buttons -->
<div class="pagination">
    {{ $books->links() }}
</div>

The links() method will generate fully functional pagination buttons (styled with Bootstrap by default, which you can customize if needed).

Bonus: Simplify with Eloquent Relationships

For cleaner code, define a many-to-many relationship in your User model:

// User model
public function wishlistBooks()
{
    return $this->belongsToMany(Book::class, 'wishlists', 'user_id', 'book_id');
}

Then your controller can be shortened to:

public function index(Request $request)
{
    $books = auth()->user()->wishlistBooks()->paginate(20);
    
    return view('wishlistCRUD.index', compact('books'))
        ->with('i', ($request->input('page', 1) - 1) * 20);
}

This follows Laravel's best practices and eliminates the need for the static myWishlist() method entirely.

内容的提问来源于stack exchange,提问作者chhhar

火山引擎 最新活动