If you want to get a single value from a specific database record, you might be inclined to do this:
$name = User::firstWhere('email', 'test@example.com')?->name;
if ($name !== null) {
//
}
But as you might know, this isn't very efficient.
Not only will this Eloquent query select columns you don't need, it also eager loads any relations the model has defined in the $with
property.
A better way to write this query, is to use Laravel's built-in value()
method:
$name = User::where('email', 'test@example.com')->value('name');
if ($name !== null) {
//
}
The value()
method selects a single column, and only returns the first row.
It is the most efficient way to select a single value from your database.
The Eloquent call above runs the following SQL query:
select `name` from `users` where `email` = 'test@example.com' limit 1
Level up your Laravel deployments
If you aren't happy with your current deployment strategy for your Laravel apps, check out my premium deployment script.
Deploy with GitHub Actions
Deploy with GitLab CI/CD