Home > Article > PHP Framework > How to implement paging function using Laravel
Laravel is a popular PHP development framework that provides many modern features and development-friendly tools, allowing developers to build websites and applications more efficiently. In the process of developing web applications, it is often necessary to display query results in pages. This article will introduce how to use Laravel to implement the paging function.
1. Introduction to paging
Paging refers to a method of splitting a large amount of data into multiple pages for display. Normally, we will set how many pieces of data to display on each page and the amount of data. When this value is exceeded, the page will turn automatically. This approach can greatly reduce page loading time and bandwidth usage, making it easier for users to view and navigate data.
2. Laravel paging operation
Laravel provides the Paginator class to implement the paging function. We can obtain the paging instance by passing the query result object to the make method of Paginator and specifying the amount of data to be displayed on each page. Call the render method on the instance, and Laravel can automatically generate pagination links.
Let’s look at the specific code implementation.
Run the following command to install Laravel:
composer create-project --prefer-dist laravel/laravel blog
Create Database table articles, and insert some sample data:
CREATE TABLE `articles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `body` text COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `articles` (`title`, `body`, `created_at`, `updated_at`) VALUES ('Article 1', 'This is article 1 content', '2021-01-01 12:00:00', '2021-01-01 12:00:00'); INSERT INTO `articles` (`title`, `body`, `created_at`, `updated_at`) VALUES ('Article 2', 'This is article 2 content', '2021-01-02 12:00:00', '2021-01-02 12:00:00'); INSERT INTO `articles` (`title`, `body`, `created_at`, `updated_at`) VALUES ('Article 3', 'This is article 3 content', '2021-01-03 12:00:00', '2021-01-03 12:00:00'); INSERT INTO `articles` (`title`, `body`, `created_at`, `updated_at`) VALUES ('Article 4', 'This is article 4 content', '2021-01-04 12:00:00', '2021-01-04 12:00:00');
Create the Article.php file in the app/Models directory and add the following code:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Article extends Model { use HasFactory; protected $fillable = ['title', 'body']; public function getDateAttribute() { return $this->created_at->format('Y-m-d'); } }
Create the ArticlesController.php file in the app/Http/Controllers directory and add the following code:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Article; class ArticlesController extends Controller { public function index(Request $request) { $articles = Article::paginate(2); return view('articles.index', compact('articles')); } }
Create the articles directory in the resources/views directory, create the index.blade.php file in this directory, and add the following code:
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8"> @foreach($articles as $article) <div class="card mb-3"> <div class="card-header"> {{ $article->title }} </div> <div class="card-body"> <p class="card-text">{{ $article->body }}</p> </div> <div class="card-footer text-right"> <small class="text-muted">{{ $article->date }}</small> </div> </div> @endforeach {{ $articles->links() }} </div> </div> </div> @endsection
Analysis:
Create the app.css file in the public/css directory and add the following code:
.card { margin-bottom: 20px; } .pagination { margin-top: 20px; }
In resources In the file app.blade.php in the /views/layouts directory, add the following code:
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <!-- Meta Tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{ config('app.name') }}</title> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm"> <div class="container"> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name') }} </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"></ul> <ul class="navbar-nav ml-auto"></ul> </div> </div> </nav> @yield('content') <script src="{{ asset('js/app.js') }}"></script> </body> </html>
Analysis:
Visit http://127.0.0.1:8000/articles and you can see that our article list has been displayed, and we You can switch between multiple pages through paging links.
What needs to be noted here is that when we call the paginate method in the controller, the parameter 2 passed in represents how many pieces of data are to be displayed on the page. If this value is set too small, the There will be a lot of paging links, causing page confusion; if this value is set too large, the amount of data displayed on the page will be very large, blocking requests for a long time, affecting the opening speed of the page, and even causing problems such as memory overflow, so it should be based on actual conditions. The situation is set carefully.
3. Summary
Laravel provides a powerful Paginator class to implement paging function, which can be easily implemented with less code. This article introduces how to use Paginator to display data in MySQL database in pages. We also showed how to use model properties in paginated results. When we need to display large amounts of data when developing websites and applications, paging is an essential feature. It can not only greatly improve the user experience, but also effectively reduce server overhead.
The above is the detailed content of How to implement paging function using Laravel. For more information, please follow other related articles on the PHP Chinese website!