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:
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:
-
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. -
This limits the number of results retrieved from the database to the first three records after the ordering has been applied.
-
This executes the query and retrieves the results as an Eloquent Collection.
-
This is a convenient method that automatically orders the results by the
created_attimestamp in ascending order. If your table hascreated_atandupdated_attimestamps, this is often a good default for fetching the oldest records