2

In the Query Builder (\Illuminate\Database\Query\Builder), it is possible to use both the skip($n) and take($n) methods.

In a Collection (\Illuminate\Support\Collection), it's possible to use the take($n) function, but there is no skip($n) function.

Why is that and is there an alternative?

Phiter
  • 14,570
  • 14
  • 50
  • 84

2 Answers2

3

The skip($n) method is indeed not included in the Collection class, but there is a function that does the same: slice($n).

QueryBuilder (taken from the documentation):

$users = DB::table('users')->skip(10)->take(5)->get();

Alternatively, you may use the limit and offset methods:

$users = DB::table('users')
                ->offset(10)
                ->limit(5)
                ->get();

Collection:

collect([1, 2, 3, 4])->slice(2)->all(); //[3, 4]

Many of the methods in the QueryBuilder class are not available in the Collection class, and vice-versa. But both of them have similar functions, like QueryBuilder's where function, you'd use Collection's filter function to achieve similar results.

Community
  • 1
  • 1
Phiter
  • 14,570
  • 14
  • 50
  • 84
0

The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();
apokryfos
  • 38,771
  • 9
  • 70
  • 114