DEV Community

Kay Gosho
Kay Gosho

Posted on • Edited on

Laravel tips: Model::findMany is useful

When you want to get multiple results of find with array of ID, you can pass the array to Model::find.

This feature started to be documented since Larave 5.2, but I found that we can use it even in Laravel 5.1.
I read Laravel source code (with no objective) then found it.

>>> App\User::find([1,2,3])

=> Illuminate\Database\Eloquent\Collection {#1090
     all: [
       App\User { id: 1 },
       App\User { id: 2 },
       App\User { id: 3 },
     ],
   }
Enter fullscreen mode Exit fullscreen mode

I used to write like User::whereIn([1, 2, 3])->get() before I found this technic.

We can also use findMany method. Actually find method runs findMany if the first argument is array.

in laravel/framework/src/Illuminate/Database/Eloquent/Builder.php

public function find($id, $columns = ['*'])
{
    if (is_array($id) || $id instanceof Arrayable) {
        return $this->findMany($id, $columns);
    }
    return $this->whereKey($id)->first($columns);
}

public function findMany($ids, $columns = ['*'])
{
    if (empty($ids)) {
        return $this->model->newCollection();
    }

    $this->query->whereIn($this->model->getQualifiedKeyName(), $ids);

    return $this->get($columns);
}
Enter fullscreen mode Exit fullscreen mode

https://github.com/laravel/framework/blob/ba0fa733243fd9b5abac67e40c9a1f7ba2ca0391/src/Illuminate/Database/Eloquent/Builder.php#L287

So we can use this method like User::findMany([1, 2, 3]).
I personally prefer this way because it is more explicit.

Top comments (2)

Collapse
 
jonathanjd profile image
Jonathan Duran

Excellent Post!

Collapse
 
acro5piano profile image
Kay Gosho

Thank you!