Table of contents

laravel find

The Laravel find method is a useful way of retrieving records from the database using the primary key. The Laravel find() method can return single or multiple rows depending on what you need to retrieve. You need to pass an integer if want to display a single row and pass an array to display multiple records. The Laravel find will return null if it could not find any available record.

 

Laravel find() Parameters

mixed $id - you can pass integer and array as I stated above if you want to display multiple results.


array $columns - the default is all columns will display but if you want to show specific columns then you can add this example: find(1, ['name']) as you can see if the table has a name field then only the name will display on the result.

 

Example #1: Single Id

In this example, we can able to use the Laravel find() method with a single ID.

public function index() 
{
    print_r(User::find(1));
}

 

Output:

App\Models\User {#1274 â–¶}

 

Example #2: Multiple Ids

In this example, we can able to pass multiple Ids using an array so that we can display multiple results.

public function index() 
{
    print_r(User::find([1,2,3]));
}

 

Output:

Illuminate\Database\Eloquent\Collection {#1275 â–¼
  #items: array:3 [â–¼
    0 => App\Models\User {#1277 â–¶}
    1 => App\Models\User {#1278 â–¶}
    2 => App\Models\User {#1279 â–¶}
  ]
  #escapeWhenCastingToString: false
}

 

 

Example 3: With Limited Column Result

In this example, we can able to limit the column result by implementing the second parameter.

public function index() 
{
    print_r(User::find(1, ['email'])->toArray());
}

//result

Array
(
    [email] => admin@gmail.com
)



public function index() 
{
    print_r(User::find([1, 2], ['email'])->toArray());
}

//result

Array
(
    [0] => Array
        (
            [email] => admin@gmail.com
        )

    [1] => Array
        (
            [email] => jcruz@gmail.com
        )

)

 

Example #4: Implement first() and last() with find() method

Implementing the first() method. In Laravel find we can also implement the first() method to display the first element of the result.

 

Here is the example code:

public function index() 
{
    print_r(User::find([1, 2], ['email'])->first()->toArray());
}

 

Implement with last() method. In this implementation, we can display the last element of the result.

public function index() 
{
    print_r(User::find([1, 2], ['email'])->last()->toArray());
}

 

 

That's pretty much it. I hope it helps. Thank you for visiting :)