Get a single database column with Eloquent's value() method
Imagine this scenario: you want to send an email, you have the user's email address, but you need their name too. You could get the name by retrieving the model from the database:
$name = User::firstWhere('email', $email)?->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.
A better way to get a single value from the database is by using Laravel's built-in value()
method:
$name = User::where('email', $email)->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
The value()
method also applies any $casts
you have defined on the model:
class User
{
public $casts = [
'status' => UserStatusEnum::class,
];
}
$status = User::where('email', $email)->value('status');
if ($status === UserStatusEnum::ACTIVE) {
//
}