LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】Illuminate\Database\Eloquent\Collection::paginate does not exist.

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

ページネーションを実装しようとしたらタイトルのエラー。

controller.php
public function show()
{
   $readHistories = $request->user()->readHistories()->paginate(25);

   return new ReadHistoryCollection($readHistories);
}
Models/User.php
public function readHistories(): Collection
{ 
   $hogeReadHistories = $this->hogeReadHistories()->get();
   $fugaReadHistories = $this->fugaReadHistories()->get();

   return $hogeReadHistories->merge($fugaReadHistories)->sortByDesc('created_at');
}

原因

$request->user()->readHistories()がcollectionで返っていて、paginateはクエリビルダかEloquentクエリのメソッドなのでエラーが起きていた。

解決法

$request->user()->readHistories()をbuilderで返るように修正する。

Models/User.php
public function readHistories(): Builder
{ 
   return ReadHistory::where('hoge_id', $this->id)
                      ->orWhere('fuga_id', $this->id)
                      ->orderByDesc('created_at');
}
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