0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelでall()の後にpaginateが使えなかった

Posted at

やりたかったこと

newsというテーブルからpaginateを使って10個ずつデータを表示したかった

やったこと

$posts = News::all()->sortBy('updated_at')->paginate(10);
newsを更新順に並べ替え手からpaginateしようとした。

結果

Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
、、怒られた。

原因

こちらの記事:Laravel Paginatorについて
に近いことが書いてあった。

ざっくり言うと、all()はcollectionを返し、collectionにpaginateなんてメソッドはない、ということだと思う。

解決方法

$posts = News::orderBy('updated_at', 'desc')->paginate(10);
にしたらうまくいった。

ここでも、sortByがcollectionメソッドだから使えなかったのでorderByを使った。
名前似てるのにややこしい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?