How to create pager in Yii2?

In controller:

function actionIndex()
{
    $query = Article::find()->where(['status' => 1]);
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    $models = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

    return $this->render('index', [
         'models' => $models,
         'pages' => $pages,
    ]);
}

In view file:

foreach ($models as $model) {
    // display $model here
}

// display pagination
echo LinkPager::widget([
    'pagination' => $pages,
]);

It is simple

$dataProvider = new ActiveDataProvider([
    'query' => User::find(),
    'pagination' => array('pageSize' => 50),
]);

echo \yii\widgets\LinkPager::widget([
    'pagination'=>$dataProvider->pagination,
]);

Or if you don't use dataProvider you should use this:

$query = User::find();
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>30]);

echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]);

Tags:

Php

Pager

Yii2