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);
Share:
46,635
Iyad Al aqel
Author by

Iyad Al aqel

Updated on October 31, 2020

Comments

  • Iyad Al aqel
    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 did DB::first('')

  • Iyad Al aqel
    Iyad Al aqel over 10 years
    This is what i have right now but i was hoping for an alternative. Thanks anyway
  • Antonio Carlos Ribeiro
    Antonio Carlos Ribeiro over 10 years
    Giving another option. But, as I said, select will return an array directly, not an object, so there are no methods.
  • Agu Dondo
    Agu Dondo about 9 years
    DB::select(DB::raw('select * from users'))[0]; triggers an undefined offset exception if no records found
  • Gras Double
    Gras Double about 8 years
    This triggers an undefined offset exception if no records found.