How to Get Last 15 Records in Laravel 10

Websolutionstuff | Dec-08-2023 | Categories : Laravel PHP MySQL

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.

Example: Retrieve the Last 15 Records using Latest() and Take()

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]);
    }
}

 

Example 2: Retrieve the Last 15 Records using orderBy()

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:

Recommended Post
Featured Post
How To Get Last 30 Days Record In Laravel 8
How To Get Last 30 Days Record...

in this tutorial, we see how to get last 30 days record in laravel 8. You can simply get the last 30 days reco...

Read More

Feb-02-2022

How To Count Days Between Two Dates In PHP Excluding Weekends
How To Count Days Between Two...

In this article, we will see how to count days between two dates in PHP excluding weekends. Here, we will learn to...

Read More

Jan-25-2023

How To Send Email With Attachment In Laravel 8
How To Send Email With Attachm...

In this tutorial i will show you how to send email with attachment in laravel 8. As we all know mail functionalities are...

Read More

May-05-2021

How to Create Components in Angular 16
How to Create Components in An...

In this article how to create components in angular 16. Here, we will learn about how to use angular component...

Read More

Jun-02-2023