Today article we will show you how to usage method limit and offset function. When should you using limit
function and offset
? In this case we will give you simple example how to use limit and offset in Laravel query builder, so that you will learn how to use offset in eloquent.
In generally, SQL statement limit and offset found in query to create pagination. The same as method in Laravel limit()
method will use to get specific data from a table and offset()
method will use for skip amount of data in specific number. We can use either limit()
or offset()
to create pagination as below example.
The example below, you can apply with Laravel 6, Laravel 7, Laravel 8 and Laravel 9 versions without any error. Let's see example below.
This is what generally we see in SQL statement.
SELECT [column_1],...,[column_n]
FROM [table_name]
ORDER BY [column_name] DESC
LIMIT [number_of_rows_to_retrieve]
OFFSET [number_of_rows_to_skip];
For instance, we want to get top 5 score students, which mean we sorted score order by descending and get first 5 records. The code should implement as below:
$score = StudentMark::select("*")
->orderBy('score','DESC')
->limit(5)
->get();
Here how we place the code in Laravel controller file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\StudentMark;
class StudentMarkController extends Controller
{
public function index()
{
// Get Top 10 highest score
$st= StudentMark::select("*")
->orderBy('score','DESC')
->offset(0)
->limit(10)
->get();
dd($st);
}
}
The below example is alternative way to create pagination record which get parameter page from client request.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\StudentMark;
class StudentMarkController extends Controller
{
private $limit= 10;
public function index()
{
// page number sent by client
$page = request("page");
// in case negative page
if($page < 1) $page = 1;
$st= StudentMark::select("*")
->offset((page - 1) * $this->limit)
->limit($this->limit)
->get();
dd($st);
}
}
Hope this short article help you with your project today. Thanks for reading.
You might also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him