Skip to main content

laravel eloquent 3 ways to fetch first 3 rows ascending

o fetch the first three rows from a table in ascending order using Laravel Eloquent ORM, you can use the following methods:
Code
use App\Models\YourModel; // Replace YourModel with your actual model name

// Method 1: Order by a specific column in ascending order and take the first 3
$records = YourModel::orderBy('column_name', 'asc')->take(3)->get();

// Method 2: If you want to order by the primary key (e.g., 'id') in ascending order
$records = YourModel::orderBy('id', 'asc')->take(3)->get();

// Method 3: Using 'oldest()' which orders by 'created_at' in ascending order by default
$records = YourModel::oldest()->take(3)->get();
Explanation:
  • YourModel::orderBy('column_name', 'asc')
    This specifies the column by which you want to sort the results and the order ('asc' for ascending, 'desc' for descending). Replace 'column_name' with the actual column you want to sort by.
  • ->take(3)
    This limits the number of results retrieved from the database to the first three records after the ordering has been applied.
  • ->get()
    This executes the query and retrieves the results as an Eloquent Collection.
  • YourModel::oldest()
    This is a convenient method that automatically orders the results by the created_at timestamp in ascending order. If your table has created_at and updated_at timestamps, this is often a good default for fetching the oldest records