How to Use find Method in Laravel Eloquent
In Laravel Eloquent, use the
find method to retrieve a record by its primary key. It returns the model instance if found or null if not. For example, User::find(1) fetches the user with ID 1.Syntax
The find method is called on an Eloquent model to fetch a record by its primary key.
Model::find($id): Returns the model instance with the given primary key ornullif not found.$id: The primary key value to search for.
php
Model::find($id);
Example
This example shows how to use find to get a user by ID and handle the case when the user does not exist.
php
<?php use App\Models\User; // Find user with ID 1 $user = User::find(1); if ($user) { echo "User found: " . $user->name; } else { echo "User not found."; }
Output
User found: John Doe
Common Pitfalls
Common mistakes when using find include:
- Expecting an exception if the record is not found (it returns
nullinstead). - Passing an array instead of a single ID (use
findManyfor multiple IDs). - Not checking for
nullbefore accessing properties, which causes errors.
php
<?php // Wrong: assuming find throws exception $user = User::find(9999); echo $user->name; // Error if user is null // Right: check for null $user = User::find(9999); if ($user) { echo $user->name; } else { echo "User not found."; }
Output
User not found.
Quick Reference
| Method | Description |
|---|---|
| find($id) | Retrieve a single record by primary key or null if not found. |
| findOrFail($id) | Retrieve a single record or throw a ModelNotFoundException if not found. |
| findMany($ids) | Retrieve multiple records by an array of primary keys. |
| first() | Retrieve the first record matching the query. |
| where() | Add conditions before calling find or other retrieval methods. |
Key Takeaways
Use
find to get a record by its primary key; it returns null if not found.Always check if the result of
find is null before accessing model properties.For multiple IDs, use
findMany instead of find.Use
findOrFail to automatically throw an error if the record is missing.The
find method is simple and efficient for quick primary key lookups.