0

Do you know why I receive all the records with this query :

$pictures = Picture::latest()->limit(100)->paginate(18);

I should only get 100, but he gives them all to me It's probably a parameter I'm forgetting but it doesn't seem illogical to me

Thanks in advance

Kylian
  • 121
  • 11
  • There's no easy solution for what you want so I suggest leaving it as is and allowing users to view all pages. There is no performance hit for doing so and it is a single line of code vs multiple and learning new concepts like custom paginations etc. – apokryfos Aug 14 '21 at 13:54

2 Answers2

3

The paginate query builder overrides your limit method.

https://laravel.com/docs/8.x/pagination#paginating-query-builder-results

Paginating Query Builder Results The paginate method automatically takes care of setting the query's "limit" and "offset" based on the current page being viewed by the user.

ImAtWar
  • 1,073
  • 3
  • 11
  • 23
  • Oh ok I see, but you have a solution for that or no ? – Kylian Aug 14 '21 at 13:10
  • Pagination is generally used to allow the user to traverse the whole data collection. You can filter the collection by applying conditions to the `where` statement. This will limit the data the user can traverse. – ImAtWar Aug 14 '21 at 13:12
  • To explain the situation, it's a photo feed, basically I display the last photos posted during the day and if there are no photos I would like to display the last 100 – Kylian Aug 14 '21 at 13:14
  • I updated my answer please check if this works – ImAtWar Aug 14 '21 at 13:26
  • Method Illuminate\Support\Collection::paginate does not exist. – Kylian Aug 14 '21 at 13:35
  • Did you use the Db facade or the Model? Could you try `Photo::take(100)->get()` and then `paginate()` ? – ImAtWar Aug 14 '21 at 13:37
  • Same error. Look the third answer here, I think it's the cause : https://stackoverflow.com/questions/48148472/laravel-method-paginate-does-not-exist – Kylian Aug 14 '21 at 13:41
  • @Kylian collections don't have the paginate method. Check [this answer](https://stackoverflow.com/a/50226837/487813) for how to create a custom paginator based on a collection result – apokryfos Aug 14 '21 at 13:55
  • Ok thanks for you help Apokryfos & ImAtWar ;) Have a nice day ! – Kylian Aug 14 '21 at 13:57
0
$pictures = Picture::latest()->simplePaginate(18);

Try simplePaginate() instead.

Brennan James
  • 332
  • 2
  • 7