LaravelのPaginatorをまとめます。
環境
php artisan tinker
使い方
object
>>> $result = App\User::where("group_id", 1)->paginate(2);
=> Illuminate\Pagination\LengthAwarePaginator {#4502
+onEachSide: 3,
}
各インスタンスメソード
>>> $result->count()
=> 2
>>> $result->total()
=> 4
>>> $result->currentPage()
=> 1
>>> $result->lastPage()
=> 2
>>> $result->firstItem()
=> 1
>>> $result->lastItem()
=> 2
>>> $result->perPage()
=> 2
>>> $result->hasMorePages()
=> true
>>> $result->nextPageUrl()
=> "https://xxxxxx.com?page=2"
>>> $result->previousPageUrl()
=> null
>>> $result->url(2)
=> "https://xxxxx.com?page=2"
>>> $result->url(1)
=> "https://xxxxx.com?page=1"
toSqlメソード
>>> App\User::where("group_id",1)->toSql()
=> "select * from `users` where `group_id` = ?"
#注意
::all()の後ろにpaginate使えない。
>>> App\User::all()->paginate(2)
BadMethodCallException with message 'Method Illuminate/Database/Eloquent/Collection::paginate does not exist.'
理由は
When you're using all() you get all the rows from the table and get a collection. Then you're using collection method where() (and not Query Builder method where()) and then you're trying to use paginate() method on the collection and it doesn't exist.