How to get the first record with laravel 4 raw queries
46,635
Solution 1
The fact is that DB:select() returns an array, so you have to:
DB::select(DB::raw('select * from users'))[0];
You also can
DB::table('users')->first();
Solution 2
Like this:
DB::table('users')->take(1)->get()[0];
Solution 3
When using eloquent you can do this:
$user = User::take(1)->get();
Solution 4
DB::table('users')->first(0);
Author by
Iyad Al aqel
Updated on October 31, 2020Comments
-
Iyad Al aqel over 3 years
How can i get the first record with laravel 4 raw queries.
Something like
DB::select('')->first();
is not working neither didDB::first('')
-
Iyad Al aqel over 10 yearsThis is what i have right now but i was hoping for an alternative. Thanks anyway
-
Antonio Carlos Ribeiro over 10 yearsGiving another option. But, as I said, select will return an array directly, not an object, so there are no methods.
-
Agu Dondo about 9 yearsDB::select(DB::raw('select * from users'))[0]; triggers an undefined offset exception if no records found
-
Gras Double about 8 yearsThis triggers an undefined offset exception if no records found.