dostoyevski
dostoyevski

Reputation: 29

getting only one record from the database in laravel

I don't know how to get just one record from the database. I'm doing it with foreach, as if it were several records. How can i get just one record? this is my code:

$usuario = \DB::select('SELECT * FROM usuarios where id=:id',['id' => session('id')]);
          foreach ($usuario as $u)
            {
                $nombre=$u->nombre;
                $email=$u->email;
            }

Upvotes: 0

Views: 280

Answers (1)

nibnut
nibnut

Reputation: 3117

As pointed out by @lagbox, you are using the select function which will return an array.

So in order to get the first element, you would do:

$usuarios = \DB::select('SELECT * FROM usuarios where id=:id',['id' => session('id')])->get();
if(!empty($usuarios)) {
    $usuario = $usuarios[0];
}

But you'd probably be better using the query builder, like this:

$usuario = \DB::table('usuarios')->where('id', session('id'))->first();
// $nombre = $usuario->nombre;
// $email = $usuario->email;

Upvotes: 2

Related Questions