Home > PHP Framework > Laravel > How to implement paging function using Laravel

How to implement paging function using Laravel

PHPz
Release: 2023-04-19 10:38:37
Original
2856 people have browsed it

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.

  1. Install Laravel

Run the following command to install Laravel:

composer create-project --prefer-dist laravel/laravel blog
Copy after login
  1. Create Mysql database table

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;
Copy after login
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');
Copy after login
  1. Define Article model

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 = [&#39;title&#39;, &#39;body&#39;];

    public function getDateAttribute()
    {
        return $this->created_at->format('Y-m-d');
    }
}
Copy after login
  1. Define ArticlesController

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(&#39;articles.index&#39;, compact(&#39;articles&#39;));
    }
}
Copy after login
  1. Create Articles view

Create the articles directory in the resources/views directory, create the index.blade.php file in this directory, and add the following code:

@extends(&#39;layouts.app&#39;)
@section(&#39;content&#39;)
    <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
Copy after login

Analysis:

  • First we display each article in a foreach loop.
  • Use the $article->title and $article->body properties to get the article title and body from the Article model.
  • Get the article publication date in the $article->date attribute.
  • Call the $articles->links() method, Laravel will automatically generate pagination links for us.
  1. Define page style

Create the app.css file in the public/css directory and add the following code:

.card {
    margin-bottom: 20px;
}
.pagination {
    margin-top: 20px;
}
Copy after login

In resources In the file app.blade.php in the /views/layouts directory, add the following code:

<!doctype html>
<html lang="{{ str_replace(&#39;_&#39;, &#39;-&#39;, 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(&#39;css/app.css&#39;) }}" 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(&#39;/&#39;) }}">
                {{ config('app.name') }}
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __(&#39;Toggle navigation&#39;) }}">
                <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(&#39;js/app.js&#39;) }}"></script>
</body>
</html>
Copy after login

Analysis:

  • Added Bootstrap4 CSS style to app.blade.php .
  • We also introduced the JS files of Bootstrap 4, but we do not need to manually introduce them ourselves, because Laravel comes with the Webpack packaging tool, which can automatically package the required JS files into public/js/app .js file.
  1. Test the paging function

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template