1

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);
Omid
  • 41
  • 5

2 Answers2

1

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()
mulkave
  • 831
  • 1
  • 10
  • 22
0

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.

Omid
  • 41
  • 5
  • Note that here you are fetching all the artifact's comments and taking a number out of them, if you wish for the query to get you the exact number right away u need to do something like `$artifact->comments()->take(10)->skip(5)->get();` – mulkave Jul 20 '16 at 07:24
  • thanks @Mulkave you're right and this is exactly what I am looking for. your solution is more efficient than mine, specially when there are lots of comments for an artifact. It is very likely in the application I'm developing. You saved me. Thanks again. – Omid Jul 20 '16 at 07:47
  • great to hear! Will put that as an answer then. – mulkave Jul 20 '16 at 13:45