Skip to content

Pagination

The paginate method is a convenient way to implement pagination for database queries in a Model class. It allows you to easily retrieve a specified number of records per page and also get information about the total number of records and pages.

Here's an overview of the method and its parameters:

    /**
    * Paginate the results.
    *
    * @param string|array $columns The columns to retrieve from the table. Default is "*" for all columns.
    * @param int $perPage The number of records to display per page. Default is 10.
    *
    * @return object An object containing the paginated results.
    */

    public static function paginate($columns = "*", $perPage = 10)

The method takes two optional parameters:

  • $columns: The columns to retrieve from the table. By default, all columns (*) are retrieved. You can pass an array of column names or a comma-separated string of column names to retrieve only specific columns.

  • $perPage: The number of records to display per page. By default, it's set to 10.

The method uses the $_GET['page'] variable to determine the current page number. If $_GET['page'] is not set, it defaults to page 1.

The method builds the SQL query by concatenating the $columns parameter with the name of the table associated with the model (stored in the $table property). It then sets the limit and offset properties of the model to limit the number of records returned and skip the appropriate number of records based on the current page number.

It then executes the query and retrieves the results using fetchAll with the PDO::FETCH_OBJ fetch mode to return the results as an array of objects.

The method also retrieves the total number of records by executing a separate query with a COUNT(*) function on the table.

Finally, the method returns an object containing the following properties:

  • results: An array of objects containing the paginated results.
  • total: The total number of records in the table.
  • nbr_pages: The total number of pages.
  • perPage: The number of records per page.
  • page: The current page number.

Here's an example of how to use the paginate method in a Model class:

    class User extends Model
    {
            protected static $table = 'users';
            protected static $fillable = ['name', 'email', 'password'];

            public static function getUsers()
            {
                    return static::paginate(['name', 'email']);
            }
    }

In this example, the getUsers method uses the paginate method to retrieve all users from the users table with only their name and email columns. The default number of records per page (10) is used. The paginate method returns an object containing the paginated results. You can then use this object to display the data on the page and create the necessary pagination links.