How to retrieve a single row from the database in Laravel
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 theget()method. Thefirst()method returns just the first match for thewhere()clause. On the other hand, theget()method returns all the records that match thewhere()clause condition. We then have to loop through those records to get the first one.