In Laravel Eloquent what is the difference between limit vs take?

Viewed 13255

In the documentation it shows the following:

To limit the number of results returned from the query, or to skip a given number of results in the query, you may use the skip and take methods:

$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();

What are the differences between these two? Are there any differences in execution speed?

4 Answers

limit only works for eloquent ORM or query builder objects, whereas take works for both collections and the ORM or Query Builder objects.

Model::get()->take(20);   // Correct
Model::get()->limit(20);  // Incorrect

Model::take(20)->get()    // Correct
Model::limit(20)->get()   // Correct

Limit works for eleqoent. Mostly used with offset

e.g

Model::offset(10)->limit(10)->get()

In the case above, it means get 10 elements(limit) starting from the 10th element onwards(offset).

Take is mostly used with collections but can also be used as an alias of limit for eloquent models

if take is used before get, it is the same as limit. If used after get, the action is performed by php itself. that is

Model ::limit(10)->get() = Model ::take(10)->get()

and take to get

Model :: take(10)->get()

Launched through Query/Builder

 public function take ($value)
 {
     return $this->limit($value);
 }}

method to be starts. Sql

select * from `table` where
  `table`.`deleted_at` is null
limit 20

If used after get

  Model :: get()->take(10);

Launched through Collection

 public function take ($limit)
 {
     if ($limit<0) {
         return $this->slice($limit, abs($limit));
     }}

     return $this->slice(0, $limit);
 }}

method worked. and all the data is retrieved via sql and then 20 are allocated via php

Sql

select * from `table` where
  `table`.`deleted_at` is null
Related