Welcome, fellow developers! In this guide, I'll walk you through the straightforward process of fetching the latest records in Laravel 10. Specifically, we'll focus on getting the last 15 records from your database using Laravel's Eloquent ORM.
In this article, I'll use the latest(), orderBy(), and take() eloquent method to get the last 15 records from the database in laravel 10.
Also, you can use this example in Laravel 7, Laravel 8, Laravel 9 and Laravel 10.
So, let's see laravel 10 gets the last 15 records, laravel gets last week's records, and laravel gets the the latest record by date.
In your controller or wherever you need to fetch the records, use the latest()
and take()
methods provided by Eloquent
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function getLast15Records(Request $request)
{
$last15Records = User::latest()->take(15)->get();
return view('home', ['records' => $last15Records]);
}
}
In this example, orderBy('id', 'desc')
is used to order the records by the id column in descending order, meaning the newest records will be fetched first.
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function getLast15Records(Request $request)
{
$last15Records = User::orderBy('id', 'DESC')->take(15)->get();
return view('home', ['records' => $last15Records]);
}
}
You might also like:
Hello, laravel web developers! In this article, we'll see how to use Quill rich text editor in laravel 11. Here, we&...
Sep-04-2024
In this article, we will see laravel 9 paypal payment gateway integration. Here, we will learn how to integrate the...
Jan-17-2023
In this article, we will see how to redirect another page using javascript. we will redirect the page to another pa...
Nov-04-2022
In the rapidly advancing world of technology, the combination of Laravel 10 and VueJS 3 is unparalleled and exceptionall...
Aug-30-2023