Laravel Fact – Eloquent Model find() can return multiple records

0
6157
Laravel Fact - Model find() can return multiple records

To get a database record from Laravel Eloquent, we make use of Model find() method to lookup. However, most of developers only know one usage to get one single record while it can be used to return multiple records.

Eloquent Model find()

When I was working on a project, I needed to query a list of records through they ID, and I used findMany(). Again, I need to double-check if something is better on Laravel official documentation. Indeed, find() can return multiple records.

Arghhhh, I was too lazy to read documentation. It’s been a while!!!

As usual, I wanted to see the implementation on find() .

Search for one record

Certainly, you’ve already known the usage of find() method, the input is the primary key value of the record we want to search for.

To be clear, here it is:

$user = App\User::find(1);

This line of code will find and return an instance of User model having id = 1. Well, just assuming that we can use default App\User model when generating a new Laravel project.

Search for multiple records

Okay, here the code I found on Laravel source, latest version 5.7 at the time of this writing.

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

Hmmm… can you see what I see?

Okay, that explains why find() can return same result as findMany().

Summary

Well, it looks like I’m pretty much out-dated to Laravel, and I need to catch up with it now.

Okay, the series of Laravel Fact will back, starting from this little tip.