How to Use first() in Laravel Eloquent: Simple Guide
In Laravel Eloquent, use the
first() method to retrieve the first record that matches your query. It returns a single model instance or null if no record is found. This is useful when you only need one result instead of a collection.Syntax
The first() method is called on an Eloquent query builder instance. It fetches the first record that matches the query conditions.
Model::where('column', 'value')->first();- returns the first matching record.Model::first();- returns the first record in the table.
If no record matches, it returns null.
php
User::where('email', 'user@example.com')->first();
Output
Returns the first User model with email 'user@example.com' or null if none found.
Example
This example shows how to get the first user with a specific email and display their name. If no user is found, it shows a message.
php
<?php use App\Models\User; $user = User::where('email', 'jane@example.com')->first(); if ($user) { echo 'User found: ' . $user->name; } else { echo 'No user found with that email.'; }
Output
User found: Jane Doe
Common Pitfalls
Common mistakes when using first() include:
- Expecting a collection instead of a single model instance.
- Not checking for
nullbefore accessing properties, causing errors. - Using
get()when only one record is needed, which is less efficient.
Always check if the result is null before using it.
php
<?php // Wrong: assuming first() returns a collection $user = User::where('id', 1)->first(); echo count($user); // Error: $user is not a collection // Right: check for null and access properties $user = User::where('id', 1)->first(); if ($user) { echo $user->name; } else { echo 'User not found'; }
Output
User not found (if no user with id 1 exists)
Quick Reference
| Method | Description |
|---|---|
| first() | Returns the first record matching the query or null if none found. |
| firstOrFail() | Returns the first record or throws an exception if none found. |
| get() | Returns a collection of all matching records. |
| find() | Finds a record by primary key and returns it or null. |
Key Takeaways
Use first() to get a single model instance matching your query or null if none found.
Always check if the result of first() is null before accessing its properties.
first() is more efficient than get() when you only need one record.
Use firstOrFail() if you want Laravel to throw an error when no record is found.
Remember first() returns a model, not a collection.