Eloquent first() if exists()
Using User::where('mobile', Input::get('mobile'))->first() is a common pattern when you expect a single record to exist. However, it throws an ErrorExceptionâ"Trying to get property of non-object"âif the query returns no results. To handle this gracefully, developers often check for existence first:
if (User::where('mobile', Input::get('mobile'))->exists()) {
$user = User::where('mobile', Input::get('mobile'))->first();
}
This approach is safe but executes two database queries. If you're working in a high-traffic application or optimizing for latency, that extra round trip matters. The core question is: can you get the first row only if it exists without running two separate queries?
The short answer is noânot with first() and exists() alone. These are distinct query operations that Laravel executes independently unless combined in a single expression. To understand why, consider what each method does under the hood:
exists()checks whether at least one row matches the condition. It typically returns early after finding the first match.first()retrieves the first matching row as an Eloquent model instance. If no rows match, it returnsnull.
Since exists() already confirms presence, calling first() afterward is redundant in terms of query logicâbut you still pay the cost of two queries. There's no built-in way to combine these behaviors into a single SQL statement that conditionally fetches a model only when data exists.
Alternative Patterns
If your goal is to avoid exceptions while minimizing queries, consider using firstOrFail() with caution. This method throws an exception if no record is found, which might reintroduce the original error unless you wrap it in a try-catch block:
try {
$user = User::where('mobile', Input::get('mobile'))->firstOrFail();
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
// Handle missing user gracefully
}
This still uses only one query but shifts the error handling strategy. You're trading an implicit exception for an explicit one, which can be cleaner in some contexts but adds complexity if you want to return a default value or null silently.
Another option is to accept null and check explicitly:
$user = User::where('mobile', Input::get('mobile'))->first();
if ($user) {
// Proceed with logic using $user
} else {
// Handle missing record
}
This approach runs a single query and avoids exceptions entirely. It's often the most straightforward solution when you don't need exists() semantics. The trade-off is that you must always check for null before accessing model properties, which can lead to verbose code if not handled carefully.
When Two Queries Are Acceptable
Sometimes the performance cost of two queries is negligible, especially if your database is fast and table sizes are small. In such cases, the clarity gained by explicitly checking existence might outweigh the minor latency hit. For instance, if you're building an admin interface where precise control over data flow is more important than micro-optimizations, the exists() + first() pattern remains valid.
Ultimately, the choice depends on your application's needs. If avoiding exceptions and reducing query count are priorities, prefer a single-query approach with null checks or try-catch blocks. If explicit existence confirmation is required for business logic, two queries may be the clearest path forward.
