Laravel find() Example
Today we will learn Laravel find() Example. The Laravel find() method can return single or multiple rows depending on what you need to get. You pass an integer then display a single row and pass an array to display multiple records. Also, The Laravel find() method returns null if it cannot find any record. The Laravel find() method is a useful way of retrieving records from the database using the primary key.
Laravel find() Example
Example 1: Single Id
We can able to use the Laravel find() method with a single ID.
public function index()
{
print_r(User::find(16));
}
Example 2: Multiple IDs
We can able to pass multiple IDs using an array so that we can display multiple records.
public function index()
{
print_r(User::find([16,17,18]));
}
Example 3: Limited Column Results
We can able to limit the column result by implementing the second parameter.
Example1
public function index()
{
print_r(User::find(16, ['email'])->toArray());
}
Output
Array
(
[email] => devnote16@gmail.com
)
Example2
public function index()
{
print_r(User::find([16, 17], ['email'])->toArray());
}
Output
Array
(
[0] => Array
(
[email] => devnote16@gmail.com
)
[1] => Array
(
[email] => devnote17@gmail.com
)
)
Example 4: Implement first() and last() with the find() method
We can also implement the first()
method to display the first element of the record.
#Example
public function index()
{
print_r(User::find([16, 17], ['email'])->first()->toArray());
}
Output
Array
(
[email] => devnote16@gmail.com
)
We can also implement the last()
method to display the last element of the record.
Example
public function index()
{
print_r(User::find([16, 17], ['email'])->last()->toArray());
}
Output
Array
(
[email] => devnote17@gmail.com
)