Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel value()
laravel
php
communitycreator

How to retrieve a single value from a query in Laravel

Chinweuba Elijah Azubuike

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, and age. However, we’re interested in email only. We’ll pass the email attribute as a parameter to the value() 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.

RELATED TAGS

laravel value()
laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring