How to fetch single row data from database in laravel

Updated at 31-Aug-2021, By samar

How to fetch single row data from database in laravel

With this article, we’ll look at some examples of how to address the "How to fetch single row data from database in laravel" problem.

You can fetch the single row data from database in laravel in different way. You can use first() method and take() method to get the single record from table.
  • First method on collection in laravel

    $user = User::first();
    return $user;
    
    //Output:
    [{"id":1,"name":"Mr. Ian Conn","email":"[email protected]","email_verified_at":"2021-08-02T00:38:40.000000Z",<br />"created_at":"2021-08-02T00:38:40.000000Z","updated_at":"2021-08-02T00:38:40.000000Z"}]
    

    You can call first method on collection to get the first item from collection in laravel. It will return the first row from user collection.

  • Get single record from users table using take() method

    $user = User::select('*')->take(1)->get();
    return $user;
    
    //Output:
    [{"id":1,"name":"Mr. Ian Conn","email":"[email protected]","email_verified_at":"2021-08-02T00:38:40.000000Z","created_at":"2021-08-02T00:38:40.000000Z","updated_at":"2021-08-02T00:38:40.000000Z"}]
    

    You can use take() method in laravel to get the specific number of records from table. To get the single record from table you have to use take(1) to table model in laravel.

Back to code snippet queries related laravel