Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel first()
laravel
php
communitycreator

How to retrieve a single row from the database in Laravel

Chinweuba Elijah Azubuike

Overview

In this shot, you will learn how to retrieve a single record from the database table using the first() method.

Syntax

$user = DB::table('users')->where('name', 'John')->first();

Parameters

The first() method does not take any parameters.

Return value

The first() method returns a single stdClass object.

Example

use Illuminate\Support\Facades\DB;

$user = DB::table('users')->where('name', 'John')->first();

Explanation

In the above example, we are fetching a single record that matches the name John in the users table.

Note: It should be noted that the first() method is different from the get() method. The first() method returns just the first match for the where() clause. On the other hand, the get() method returns all the records that match the where() clause condition. We then have to loop through those records to get the first one.

RELATED TAGS

laravel first()
laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring