Get a single database column with Eloquent's value() method
Published on
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) {
//
}
The code above 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.
You can improve this query by using 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 query above runs the following SQL query:
select `name` from `users` where `email` = 'test@example.com' limit 1