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.
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.
$email = DB::table('users')->where('name', 'John')->value('email');
The value()
method takes one parameter:
name
, email
, and age
. However, we’re interested in email
only. We’ll pass the email
attribute as a parameter to the value()
method.value()
method returns a single value from the retrieved row or record.
use Illuminate\Support\Facades\DB;
public function getEmail(){
$email= DB::table('users')->where('name', 'John')->value('email');
return $email;
}
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.