Hello developers! In this article, we'll see how to get the last 15 records in laravel 10. Here, we'll get the latest record by ID in laravel 10. In this guide, I'll show you how to fetch the latest records in Laravel 10. Specifically, we'll look at how to get 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.
Let's dive into how to get the last 15 records, the records from last week, and the latest record by date in Laravel.
First, let's see how to get the last 15 records using the latest()
and take()
methods.
app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Fetch the last 15 records
*
* @return \Illuminate\Http\Response
*/
public function getLast15Records(Request $request)
{
$last15Records = User::latest()->take(15)->get();
return view('home', ['records' => $last15Records]);
}
}
Another way to get the last 15 records is by using the orderBy()
method. 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:
- Read Also: How to Send Mail using Markdown Template in Laravel 10
- Read Also: How to Create Multiple Database Connections in Laravel 10
- Read Also: How to Import Excel File into Database using Python
- Read Also: How To Integrate Paypal Payment Gateway In Laravel 10