LoginSignup
0
3

More than 3 years have passed since last update.

Laravel Paginatorについて

Last updated at Posted at 2020-06-18

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.

参考

0
3
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
3