133

This might be a simple question, but I cannot figure this out. I am trying to get a user by email using:

$user = User::whereEmail($email)->get();

But this is returning an array (of dimension 1) of $users. So If I want to get the name, I have to do $user[0]['first_name'].

I tried using limit(1) or take(1), or even using ->toArray() but there was no difference.

What am I doing wrong?

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • 1
    You want to get one row from queried result? Or you just want one row from database query? –  May 29 '14 at 05:25

7 Answers7

275

Simply use this:

$user = User::whereEmail($email)->first();
EM-Creations
  • 4,195
  • 4
  • 40
  • 56
Ganesh Jogam
  • 3,117
  • 1
  • 13
  • 10
28

There are multiple ways.

1. By using Model. Example:

User::where('column_name', 'value')->first();

Before you use this you must declare the DB facade in the controller Simply put this line for that

use Illuminate\Support\Facades\DB;

Now you can get a row using this

$getUserByEmail = DB::table('users')->where('email', $email)->first();

or by this too

3.

$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['useremailaddress@email.com']);

This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.

Hope this helps.

Koushik Das
  • 9,678
  • 3
  • 51
  • 50
11

Using Laravel Eloquent you can get one row using first() method,

it returns first row of table if where() condition is not found otherwise it gives the first matched row of given criteria.

Syntax:

Model::where('fieldname',$value)->first();

Example:

$user = User::where('email',$email)->first(); 
//OR
//$user = User::whereEmail($email)->first();
Haritsinh Gohil
  • 5,818
  • 48
  • 50
3

Try with it

$color = \App\Color::take(1)->first();
Mahedi Hasan Durjoy
  • 1,031
  • 13
  • 17
2

laravel 5.8

If you don't even need an entire row, you may extract a single value from a record using the value() method. This method will return the value of the column directly:

$first_name = DB::table('users')->where('email' ,'me@mail,com')->value('first_name');

check docs

Hussam Adil
  • 502
  • 7
  • 13
-2

In your given code, simply use this:

$user = User::whereEmail($email)->first()->first_name
Faridul Khan
  • 1,741
  • 1
  • 16
  • 27
-5
$getUserByEmail = DB::select("SELECT * FROM users WHERE email = $email"]);