how do I use skip/take in Vinelab/Neoeloquent queries: PHP

195 Views Asked by At

I want to limit the number of results given by a Neoeloquent query, take() works fine but I don't know how should I use skip()? I read the laravel 5.2 Doc. I'm trying to use skip(10)->take(10) but it says "Method skip does not exist." here is my code:

$artifact=Models\Artifact::where('aid',$request->aid)->first();
$comments=$artifact->comments->take(10);
2

There are 2 best solutions below

3
On

ok, I found an answer to my own question, since the result set of $artifact->comments is a laravel collection, there is no skip() method. using another method named slice() I could solve the problem and get my desired subset of result. Now I have:

$comments=$artifact->comments->slice($startOffset, $count);

which works fine. Another method named splice() returns similar values but please consider that it will modify the original result set.

0
On

With the answer you provided what happens is that you will be fetching all of the comments so with a large number of them it will be a bottleneck on performance especially that you do not need all of them. What you can do is use limit and offset on the query with the methods take and skip respectively, as follows:

$comments = $artifact->comments()->take(10)->skip(5)->get()