How to retrieve a single value from a query in Laravel
Introduction
Sometimes you just want the value of a retrieved record. This is mostly used when retrieving a status value but can be used for other specific purposes as well as per the needs and requirements.
In this shot, we’ll learn how to retrieve a single value from a record using the value() method.
What is the value() method?
The value() method is a query builder method that is chained to other queries to get a single value from the retrieved row or record.
Syntax
$email = DB::table('users')->where('name', 'John')->value('email');
Parameters
The value() method takes one parameter:
- Attribute name: In a row, there can be multiple attributes such as
name,email, andage. However, we’re interested inemailonly. We’ll pass theemailattribute as a parameter to thevalue()method.
Return value
value() method returns a single value from the retrieved row or record.
Example
use Illuminate\Support\Facades\DB;
public function getEmail(){
$email= DB::table('users')->where('name', 'John')->value('email');
return $email;
}
Explanation
In the example above, we create a function getEmail(). Inside this function, we get the table using the table() method. Next, we get a match for the record we’re looking for using the where() clause. Finally, we use the value() method to retrieve the value and return it. In this example, we return the email of the user.