Inside this article we will see the concept i.e Laravel 9 How To Get Last 5 Records Using Model Tutorial. Article contains the classified information about How to get last 10 records / latest records in laravel.
If you are looking for a solution i.e How to get last 5 records in laravel then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.
In laravel there are few methods available which helps you for this latest record from your database table – latest(), orderBy().
Read More: Laravel 9 How To Set Default Values in Model For Columns
Let’s get started.
Laravel Installation
Open terminal and run this command to create a laravel project.
composer create-project laravel/laravel myblog
It will create a project folder with name myblog inside your local system.
To start the development server of laravel –
php artisan serve
URL: http://127.0.0.1:8000
Assuming laravel already installed inside your system.
Create Database & Connect
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
CREATE DATABASE laravel_app;
To connect database with application, Open .env file from application root. Search for DB_ and update your details.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_app DB_USERNAME=root DB_PASSWORD=root
Example #1: Get Latest Records Using orderBy()
Suppose, you have a posts table. A Post Model and a PostController.
Read More: Laravel 9 How To Get Request Headers Example Tutorial
Next, you want to fetch last 5 records from it. Use this concept of orderBy() to get that.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller { public function index() { $posts = Post::orderBy("id", "DESC")->take(5)->get(); dd($posts); } }
Example #2: Get Latest Records Using latest()
You want to fetch last 5 records from it. Use this concept of latest() to get that.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller { public function index() { $posts = Post::latest()->take(5)->get(); dd($posts); } }
We hope this article helped you to learn Laravel 9 How To Get Last 5 Records Using Model Example Tutorial in a very detailed way.
Read More: Laravel 9 How To Get Database Name Example Tutorial
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.