Laravel 5中的自定义分页视图

时间:2015-01-30 16:53:48

标签: php pagination laravel-5

Laravel 4.2 可以选择在app/config/view.php中指定自定义视图,例如:

/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
'pagination' => 'pagination_slider-alt'

Laravel 5 至少关于view.php

有没有办法在 Laravel 5 中复制此行为?

20 个答案:

答案 0 :(得分:104)

Laravel 5.3+使用

$users->links('view.name')

Laravel 5.0 - 5.2 而不是

$users->render()

使用

@include('pagination.default', ['paginator' => $users])

视图/分页/ default.blade.php

@if ($paginator->lastPage() > 1)
<ul class="pagination">
    <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
        <a href="{{ $paginator->url(1) }}">Previous</a>
    </li>
    @for ($i = 1; $i <= $paginator->lastPage(); $i++)
        <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
            <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
        </li>
    @endfor
    <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
        <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
    </li>
</ul>
@endif

就是这样。

如果您有很多页面,请使用此模板:

视图/分页/ limit_links.blade.php

<?php
// config
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>

@if ($paginator->lastPage() > 1)
    <ul class="pagination">
        <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
            <a href="{{ $paginator->url(1) }}">First</a>
         </li>
        @for ($i = 1; $i <= $paginator->lastPage(); $i++)
            <?php
            $half_total_links = floor($link_limit / 2);
            $from = $paginator->currentPage() - $half_total_links;
            $to = $paginator->currentPage() + $half_total_links;
            if ($paginator->currentPage() < $half_total_links) {
               $to += $half_total_links - $paginator->currentPage();
            }
            if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
                $from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
            }
            ?>
            @if ($from < $i && $i < $to)
                <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                    <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
                </li>
            @endif
        @endfor
        <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
            <a href="{{ $paginator->url($paginator->lastPage()) }}">Last</a>
        </li>
    </ul>
@endif

答案 1 :(得分:22)

对于Laravel 5.3(可能在其他5.X版本中)将自定义分页代码放在您的视图文件夹中。

  

资源/视图/分页/ default.blade.php

@if ($paginator->hasPages())
    <ul class="pagination">
        {{-- Previous Page Link --}}
        @if ($paginator->onFirstPage())
            <li class="disabled"><span>&laquo;</span></li>
        @else
            <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">&laquo;</a></li>
        @endif

        {{-- Pagination Elements --}}
        @foreach ($elements as $element)
            {{-- "Three Dots" Separator --}}
            @if (is_string($element))
                <li class="disabled"><span>{{ $element }}</span></li>
            @endif

            {{-- Array Of Links --}}
            @if (is_array($element))
                @foreach ($element as $page => $url)
                    @if ($page == $paginator->currentPage())
                        <li class="active"><span>{{ $page }}</span></li>
                    @else
                        <li><a href="{{ $url }}">{{ $page }}</a></li>
                    @endif
                @endforeach
            @endif
        @endforeach

        {{-- Next Page Link --}}
        @if ($paginator->hasMorePages())
            <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">&raquo;</a></li>
        @else
            <li class="disabled"><span>&raquo;</span></li>
        @endif
    </ul>
@endif

然后从主视图文件中调用此分页视图文件为

{{ $posts->links('pagination.default') }}

根据需要更新pagination / default.blade.php

答案 2 :(得分:22)

在Laravel 5中,自定义分页基于演示者(类)而不是视图。

假设你的路由代码中有

$users = Users::paginate(15);

在L4中,您曾经在视图中执行过类似的操作:

$users->appends(['sort' => 'votes'])->links();

在L5中你改为:

$users->appends(['sort' => 'votes'])->render();

render()方法接受Illuminate\Contracts\Pagination\Presenter实例。您可以创建实现该合同的自定义类,并将其传递给render()方法。请注意,Presenter界面,而不是类,因此您必须实施,而不是扩展。这就是你收到错误的原因。

或者,您可以扩展Laravel paginator(以便使用其分页逻辑),然后将现有的分页实例($users->...)传递给扩展类构造函数。这确实是我根据Laravel提供的Bootstrap演示者创建自定义Zurb Foundation演示者所做的。它使用所有Laravel分页逻辑,只覆盖渲染方法。

使用我的自定义演示者,我的观点如下:

with(new \Stolz\Laravel\Pagination($users->appends(['sort' => 'votes'])))->render();

我定制的分页主持人是:

<?php namespace Stolz\Laravel;

use Illuminate\Pagination\BootstrapThreePresenter;

class Pagination extends BootstrapThreePresenter
{
    /**
     * Convert the URL window into Zurb Foundation HTML.
     *
     * @return string
     */
    public function render()
    {
        if( ! $this->hasPages())
            return '';

        return sprintf(
            '<ul class="pagination" aria-label="Pagination">%s %s %s</ul></div>',
            $this->getPreviousButton(),
            $this->getLinks(),
            $this->getNextButton()
        );
    }

    /**
     * Get HTML wrapper for disabled text.
     *
     * @param  string  $text
     * @return string
     */
    protected function getDisabledTextWrapper($text)
    {
        return '<li class="unavailable" aria-disabled="true"><a href="javascript:void(0)">'.$text.'</a></li>';
    }

    /**
     * Get HTML wrapper for active text.
     *
     * @param  string  $text
     * @return string
     */
    protected function getActivePageWrapper($text)
    {
        return '<li class="current"><a href="javascript:void(0)">'.$text.'</a></li>';
    }

    /**
     * Get a pagination "dot" element.
     *
     * @return string
     */
    protected function getDots()
    {
        return $this->getDisabledTextWrapper('&hellip;');
    }
}

答案 3 :(得分:12)

然而在 Laravel 4.2 中,我会使用:

{{ $users->links('view.name') }}

Laravel 5 中,您可以使用以下内容复制上述内容:

@include('view.name', ['object' => $users])

现在,在随附的视图中,$object将提供分页方法,例如currentPage()lastPage()perPage()等。

您可以在http://laravel.com/docs/5.0/pagination

查看所有可用的方法

答案 4 :(得分:6)

5.5 links()中,render()替换为似乎有效的{{ $replies->links() }} [Official DOC]

替换

{{ $replies->render("pagination::default") }}

resources/views/vendor/pagination

以下命令将在artisan vendor:publish --tag=laravel-pagination artisan vendor:publish

中生成分页模板
{{ $replies->render("pagination::default") }}

在任何视图文件(刀片文件)中,您都可以使用以下ex:

之类的模板
  • {{ $replies->render("pagination::bootstrap-4") }}
  • {{ $replies->render("pagination::simple-bootstrap-4") }}
  • {{ $replies->render("pagination::semantic-ui") }}
  • let bookList = [ ["title" : "Harry Potter", "author" : "Joan K. Rowling" "image" : image // UIImage is added. ], ["title" : "Twilight", "author" : " Stephenie Meyer", "image" : image ], ["title" : "The Lord of the Rings", "author" : "J. R. R. Tolkien", "image" : image]

答案 5 :(得分:6)

如果有人需要,Laravel 5附带Bootstrap 4 paginator

首先创建一个新的服务提供商。

php artisan make:provider PaginationServiceProvider

register方法中,将一个闭包传递给Laravel的paginator类,该类创建并返回新的演示者。

<?php


namespace App\Providers;

use Illuminate\Pagination\BootstrapFourPresenter;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class PaginationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        Paginator::presenter(function($paginator)
        {
            return new BootstrapFourPresenter($paginator);
        });
    }
}

config/app.php

中注册新的提供商
'providers' => [
    //....
    App\Providers\PaginationServiceProvider::class,
]

我在Bootstrap 4 Pagination With Laravel

找到了这个例子

答案 6 :(得分:5)

也许为时已晚,但我想分享另一个我创建的自定义分页模板,它创建了第一个/下一个和最后一个/上一个链接。当用户已经在第一页/最后一页时,它也会隐藏链接。

(可选)您还可以确定链接的间隔(当前页面之前和之后的链接数量)

用法示例:

 @include('pagination', ['paginator' => $users])

@include('pagination', ['paginator' => $users, 'interval' => 5])

这是要点:https://gist.github.com/carloscarucce/33f6082d009c20f77499252b89c35dea

代码:

@if (isset($paginator) && $paginator->lastPage() > 1)

    <ul class="pagination">

        <?php
        $interval = isset($interval) ? abs(intval($interval)) : 3 ;
        $from = $paginator->currentPage() - $interval;
        if($from < 1){
            $from = 1;
        }

        $to = $paginator->currentPage() + $interval;
        if($to > $paginator->lastPage()){
            $to = $paginator->lastPage();
        }
        ?>

        <!-- first/previous -->
        @if($paginator->currentPage() > 1)
            <li>
                <a href="{{ $paginator->url(1) }}" aria-label="First">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>

            <li>
                <a href="{{ $paginator->url($paginator->currentPage() - 1) }}" aria-label="Previous">
                    <span aria-hidden="true">&lsaquo;</span>
                </a>
            </li>
        @endif

        <!-- links -->
        @for($i = $from; $i <= $to; $i++)
            <?php 
            $isCurrentPage = $paginator->currentPage() == $i;
            ?>
            <li class="{{ $isCurrentPage ? 'active' : '' }}">
                <a href="{{ !$isCurrentPage ? $paginator->url($i) : '#' }}">
                    {{ $i }}
                </a>
            </li>
        @endfor

        <!-- next/last -->
        @if($paginator->currentPage() < $paginator->lastPage())
            <li>
                <a href="{{ $paginator->url($paginator->currentPage() + 1) }}" aria-label="Next">
                    <span aria-hidden="true">&rsaquo;</span>
                </a>
            </li>

            <li>
                <a href="{{ $paginator->url($paginator->lastpage()) }}" aria-label="Last">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        @endif

    </ul>

@endif

答案 7 :(得分:3)

Laravel 5.2为此使用演示者。您可以创建自定义演示者或使用预定义的演示者。 Laravel 5.2使用开箱即用的BootstrapThreePrensenter,但很容易使用BootstrapFroutPresenter或任何其他自定义演示者。

public function index()
{
    return view('pages.guestbook',['entries'=>GuestbookEntry::paginate(25)]);
}

在您的刀片模板中,您可以使用以下公式:

{!! $entries->render(new \Illuminate\Pagination\BootstrapFourPresenter($entries)) !!}

要创建自定义演示者,我建议您观看Codecourse's video

答案 8 :(得分:2)

Laravel 5 +

中Bootstrap 4分页的快速JS修复

只需将以下脚本放在您的页面中:

    <script>
            $('.pagination li').addClass('page-item');
            $('.pagination li a').addClass('page-link');
            $('.pagination span').addClass('page-link');

    </script>

优点:节省服务器CPU,无需在应用程序中进行调整。

答案 9 :(得分:2)

如果你想美化你的分页的外观,我使用bootstrap中的类来使它更简单和容易

 @if ($students->lastPage() > 1)
        <ul class="pagination ml-auto">
            <li class="{{ ($students->currentPage() == 1) ? ' disabled' : '' }} page-item">
                <a class=" page-link " href="{{ $students->url(1) }}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                    <span class="sr-only">Previous</span>
                </a>
            </li>
            @for ($i = 1; $i <= $students->lastPage(); $i++)
                <li class="{{ ($students->currentPage() == $i) ? ' active' : '' }} page-item">
                    <a class=" page-link " href="{{ $students->url($i) }}">{{ $i }}</a>
                </li>
            @endfor
            <li class="{{ ($students->currentPage() == $students->lastPage()) ? ' disabled' : '' }} page-item">
                <a href="{{ $students->url($students->currentPage()+1) }}" class="page-link" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                    <span class="sr-only">Next</span>
                </a>
            </li>
        </ul>
@endif

答案 10 :(得分:1)

除了@MantasD的回答我想提供全面的定制Laravel分页。假设使用Laravel 5.2和以下包含视图:

$no = get-content no_stop.txt;
Get-Process example* | Where { $no -notcontains $_.Name } | kill -Force

功能

  • 显示上一个和下一个按钮,并在不适用时禁用它们
  • 仅当“上一页”和“下一页”不相同时才显示“第一页”和“最后一页”图标
  • 生成相对链接ex:(10,100,500 ...等)而不是限制页面
  • 使用辅助函数显示每页x到y的结果。

<强> default.blade.php

@include('pagination.default', ['pager' => $users])

PaginationStartEnd功能

@if($pager->lastPage() != 1)
<ul class="pagination">

    @unless($pager->currentPage() < 3)
        <li class="paginate_button previous">
            <a href="{{ $pager->url(1) }}" title="First Page"><i class="fa fa-angle-double-left"></i></a>
        </li>
    @endunless

    <li class="paginate_button previous @unless($pager->previousPageUrl())disabled @endunless">
        <a href="{{ $pager->previousPageUrl() }}"><i class="fa fa-angle-left"></i></a>
    </li>

    @while($pager->paging++ < $pager->lastPage())
        @if (abs($pager->paging - $pager->currentPage()) >= 2)
            {{-- Generate relative links (eg. +10,etc) --}}
            @if(in_array(abs($pager->paging - $pager->currentPage()), array(10, 50, 100, 500, 1000))
            and $pager->paging != 1 and $pager->paging != $pager->lastPage())
                <li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
                    <a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
                        <!-- + {{ $pager->paging - $pager->currentPage() }} -->{{ $pager->paging }}
                    </a>
                </li>
            @endif
        @else
            <li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
                <a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
                    {{ $pager->paging }}
                </a>
            </li>
        @endif
    @endwhile

    <li class="paginate_button next @unless($pager->nextPageUrl())disabled @endunless">
        <a href="{{ $pager->nextPageUrl() }}"><i class="fa fa-angle-right"></i></a>
    </li>

    @unless($pager->lastPage() - $pager->currentPage() < 2)
        <li class="paginate_button next">
            <a href="{{ $pager->url($pager->lastPage()) }}" title="Last Page"><i class="fa fa-angle-double-right"></i></a>
        </li>
    @endunless

</ul>
@endif

您可以根据需要更多地使用和自定义。

注意: $ pager-&gt;分页是在控制器操作中声明的变量设置为

答案 11 :(得分:1)

这是Laravel 5,Bootstrap 4和没有Blade语法的一个(对于那些找到它的人infinitely harder to read)。

使用,而不是:

{!! $users->render() !!}

使用:

@include('partials/pagination', ['paginator' => $users])

partials/pagination是您的刀片模板文件,其中粘贴了以下内容。

// Number of links to show. Odd numbers work better
$linkCount = 7;
$pageCount = $paginator->lastPage();

if ($pageCount > 1)
{
    $currentPage = $paginator->currentPage();
    $pagesEitherWay = floor($linkCount / 2);
    $paginationHtml = '<ul class="pagination">';

    // Previous item
    $previousDisabled = $currentPage == 1 ? 'disabled' : '';
    $paginationHtml .= '<li class="page-item '.$previousDisabled.'">
                            <a class="page-link" href="'.$paginator->url($currentPage - 1).'" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                                <span class="sr-only">Previous</span>
                            </a>
                        </li>';

    // Set the first and last pages
    $startPage = ($currentPage - $pagesEitherWay) < 1 ? 1 : $currentPage - $pagesEitherWay;
    $endPage = ($currentPage + $pagesEitherWay) > $pageCount ? $pageCount : ($currentPage + $pagesEitherWay);

    // Alter if the start is too close to the end of the list
    if ($startPage > $pageCount - $linkCount)
    {
        $startPage = ($pageCount - $linkCount) + 1;
        $endPage = $pageCount;
    }

    // Alter if the end is too close to the start of the list
    if ($endPage <= $linkCount)
    {
        $startPage = 1;
        $endPage = $linkCount < $pageCount ? $linkCount : $pageCount;
    }

    // Loop through and collect
    for ($i = $startPage; $i <= $endPage; $i++)
    {
        $disabledClass = $i == $currentPage ? 'disabled' : '';
        $paginationHtml .= '<li class="page-item '.$disabledClass.'">
                                <a class="page-link" href="'.$paginator->url($i).'">'.$i.'</a>
                            </li>';
    }

    // Next item
    $nextDisabled = $currentPage == $pageCount ? 'disabled' : '';
    $paginationHtml .= '<li class="page-item '.$nextDisabled.'">
                            <a class="page-link" href="'.$paginator->url($currentPage + 1).'" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                                <span class="sr-only">Next</span>
                            </a>
                        </li>';

    $paginationHtml .= '</ul>';

    echo $paginationHtml;
}

答案 12 :(得分:1)

我正在使用 Laravel 5.8 。任务是像下一个http://some-url / page-N 一样进行分页,而不是http://some-url ?page = N 。无法通过编辑/resources/views/vendor/pagination/blade-name-here.blade.php模板来完成(它可以由 php artisan vendor:publish --tag = laravel-pagination 命令)。在这里,我不得不扩展核心类。

我的模型使用了 DB 实例的 paginate 方法,如下所示:

        $essays = DB::table($this->table)
        ->select('essays.*', 'categories.name', 'categories.id as category_id')
        ->join('categories', 'categories.id', '=', 'essays.category_id')
        ->where('category_id', $categoryId)
        ->where('is_published', $isPublished)
        ->orderBy('h1')
        ->paginate( // here I need to extend this method
            $perPage,
            '*',
            'page',
            $page
        );

开始吧。 paginate()方法放在 \ Illuminate \ Database \ Query \ Builder 内部,并返回 Illuminate \ Pagination \ LengthAwarePaginator 对象。 LengthAwarePaginator 扩展了 Illuminate \ Pagination \ AbstractPaginator ,它具有公共函数url($ page)方法,需要扩展:

    /**
 * Get the URL for a given page number.
 *
 * @param  int  $page
 * @return string
 */
public function url($page)
{
    if ($page <= 0) {
        $page = 1;
    }

    // If we have any extra query string key / value pairs that need to be added
    // onto the URL, we will put them in query string form and then attach it
    // to the URL. This allows for extra information like sortings storage.
    $parameters = [$this->pageName => $page];

    if (count($this->query) > 0) {
        $parameters = array_merge($this->query, $parameters);
    }

    // this part should be overwrited
    return $this->path 
        . (Str::contains($this->path, '?') ? '&' : '?')
        . Arr::query($parameters)
        . $this->buildFragment();
}

分步指南(我从this一篇不错的文章中摘录的部分信息):

    app 目录中
  1. 创建扩展文件夹。
  2. 扩展文件夹中创建3个文件 CustomConnection.php,CustomLengthAwarePaginator.php,CustomQueryBuilder.php

2.1 CustomConnection.php文件:

namespace App\Extended;

use \Illuminate\Database\MySqlConnection;

/**
 * Class CustomConnection
 * @package App\Extended
 */
class CustomConnection extends MySqlConnection {
    /**
     * Get a new query builder instance.
     *
     * @return \App\Extended\CustomQueryBuilder
     */
    public function query() {
        // Here core QueryBuilder is overwrited by CustomQueryBuilder
        return new CustomQueryBuilder(
            $this,
            $this->getQueryGrammar(),
            $this->getPostProcessor()
        );
    }
}

2.2 CustomLengthAwarePaginator.php文件-该文件包含需要覆盖的信息的主要部分:

namespace App\Extended;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

/**
 * Class CustomLengthAwarePaginator
 * @package App\Extended
 */
class CustomLengthAwarePaginator extends LengthAwarePaginator
{
    /**
     * Get the URL for a given page number.
     * Overwrited parent class method
     *
     *
     * @param  int  $page
     * @return string
     */
    public function url($page)
    {
        if ($page <= 0) {
            $page = 1;
        }

        // here the MAIN overwrited part of code BEGIN
        $parameters = [];

        if (count($this->query) > 0) {
            $parameters = array_merge($this->query, $parameters);
        }

        $path =  $this->path . "/{$this->pageName}-$page";
        // here the MAIN overwrited part of code END

        if($parameters) {
            $path .= (Str::contains($this->path, '?') ? '&' : '?') . Arr::query($parameters);
        }

        $path .= $this->buildFragment();

        return $path;
    }
}

2.3 CustomQueryBuilder.php文件:

namespace App\Extended;

use Illuminate\Container\Container;
use \Illuminate\Database\Query\Builder;

/**
 * Class CustomQueryBuilder
 * @package App\Extended
 */
class CustomQueryBuilder extends Builder
{
    /**
     * Create a new length-aware paginator instance.
     * Overwrite paginator's class, which will be used for pagination
     *
     * @param  \Illuminate\Support\Collection  $items
     * @param  int  $total
     * @param  int  $perPage
     * @param  int  $currentPage
     * @param  array  $options
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    protected function paginator($items, $total, $perPage, $currentPage, $options)
    {
        // here changed
        // CustomLengthAwarePaginator instead of LengthAwarePaginator
        return Container::getInstance()->makeWith(CustomLengthAwarePaginator::class, compact(
            'items', 'total', 'perPage', 'currentPage', 'options'
        ));
    }
}
  1. /config/app.php 中需要更改数据库提供程序:

    'providers' => [
    
    
    // comment this line        
    // illuminate\Database\DatabaseServiceProvider::class,
    
    // and add instead:
    App\Providers\CustomDatabaseServiceProvider::class,
    
  2. 在控制器中(或从db接收分页数据的其他地方),您需要更改分页设置:

    // here are paginated results
    $essaysPaginated = $essaysModel->getEssaysByCategoryIdPaginated($id, config('custom.essaysPerPage'), $page);
    // init your current page url (without pagination part)
    // like http://your-site-url/your-current-page-url
    $customUrl = "/my-current-url-here";
    // set url part to paginated results before showing to avoid 
    // pagination like http://your-site-url/your-current-page-url/page-2/page-3 in pagination buttons
    $essaysPaginated->withPath($customUrl);
    
  3. 在视图中添加分页链接(/resources/views/your-controller/your-blade-file.blade.php),如下所示:

    <nav>
        {!!$essays->onEachSide(5)->links('vendor.pagination.bootstrap-4')!!}
    </nav>
    

享受! :)您的自定义分页现在应该可以使用

答案 13 :(得分:1)

如果您想使用 next 和 prev 自定义分页链接。 你可以在 Paginator.php 看到 在里面,有一些方法 我正在使用 Laravel 7

chmod 777

要限制项目,在控制器中使用 paginate()

<a href="{{ $paginator->previousPageUrl() }}" < </a>
<a href="{{ $paginator->nextPageUrl() }}" > </a>

答案 14 :(得分:0)

感谢MantisD的帖子,对于Bootstrap 4,这很好用。

<?php
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>

@if ($paginator->lastPage() > 1)
    <div id="news_paginate" class="dataTables_paginate paging_simple_numbers">
        <ul class="pagination">
            <li id="news_previous" class="paginate_button page-item previous {{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
                <a class="page-link" tabindex="0" href="{{ $paginator->url(1) }}">Previous</a>
            </li>
            @for ($i = 1; $i <= $paginator->lastPage(); $i++)
                <?php
                    $half_total_links = floor($link_limit / 2);
                    $from = $paginator->currentPage() - $half_total_links;
                    $to = $paginator->currentPage() + $half_total_links;
                    if ($paginator->currentPage() < $half_total_links) {
                        $to += $half_total_links - $paginator->currentPage();
                    }
                    if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
                        $from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
                    }
                ?>
                @if ($from < $i && $i < $to)
                    <li class="paginate_button page-item {{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                        <a class="page-link" href="{{ $paginator->url($i) }}">{{ $i }}</a>
                    </li>
                @endif
            @endfor
            <li id="news_next" class="paginate_button page-item {{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
                @if($paginator->currentPage() == $paginator->lastPage())
                    <a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()) }}" >End</a>
                @else
                    <a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
                @endif
            </li>
        </ul>
    </div>
@endif

答案 15 :(得分:0)

如果您想更改网址中的网页编号而不是像/ pageNo那样获取数据。例如: / 2。你可以使用jquery来改变网址。我在ur方法的get方法中有一些数据。

$(function () {
  $('.pagination li a').each(function () {
    var link = $(this).attr('href');
    var pageText = $(this).text();
    var activePage = parseInt($('.pagination li.active span').text());
    if (pageText.trim() == "«") {
      pageText = activePage - 1;
    } else if (pageText.trim() == "»") {
      pageText = activePage + 1;
    }
    link = link.replace('?', '/' + pageText + '?');
    link = link.replace('&page=' + pageText, '');
    $(this).attr('href', link);
    console.log(link);
  });
})

答案 16 :(得分:0)

您好我的分页代码:在刀片中使用 @include('pagination.default',['paginator'=&gt; $ users])

Views / pagination / default.blade.php

@if ($paginator->lastPage() > 1)

si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
    <!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
    @if($paginator->currentPage() != 1)
        <li>
            <a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
                <
            </a>
        </li>
    @endif

    <!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
    <!-- I draw the pages... I show 2 pages back and 2 pages forward -->
    @for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
            <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
            </li>
    @endfor

    <!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
    <!-- if actual page is not equal last page then I show the forward button-->
    @if ($paginator->currentPage() != $paginator->lastPage())
        <li>
            <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
                >
            </a>
        </li>
    @endif

    <!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
    <!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
    @if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
        <li>
            <a href="{{ $paginator->url($paginator->lastPage()) }}" >
                >>
            </a>
        </li>
    @endif
</ul>

答案 17 :(得分:0)

在Laravel 5.4中

我发现的最简单的方法是使用resources/views/vendor命令将它们导出到vendor:publish目录

php artisan vendor:publish --tag=laravel-pagination

然后转到resources\views\vendor\pagination\default.blade.php

并在那里进行自定义。

可以找到有关此内容的完整文档here

答案 18 :(得分:0)

我将此代码与k7主题一起使用,并将此代码与其内置类一起使用。 您也可以根据需要将此代码与您的主题和课程一起使用..

尝试这样做。

<section class="page-paging pt-0">
  <div class="container">
    <div class="row">
      <div class="col-12">
        <nav aria-label="Page navigation example">
          @if ($view_post->lastPage() > 1)
            <ul class="pager list-inline mb-0 text-center">
              <li class="{{ ($view_post->currentPage() == 1) ? ' disabled' : '' }}p-1 list-inline-item float-sm-left">
                <a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url(1) }}">
                  <i class="fa fa-angle-left pr-1"></i> Prev
                </a>
              </li>
              @for ($i = 1; $i <= $view_post->lastPage(); $i++)
              <li class=" p-1 list-inline-item d-none d-md-inline-block">
                <a class="{{ ($view_post->currentPage() == $i) ? ' active' : '' }} page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($i) }}">{{ $i }}
                </a>
              </li>
              @endfor
              <li class="{{ ($view_post->currentPage() == $view_post->lastPage()) ? ' disabled' : '' }} p-1 list-inline-item float-sm-right">
                <a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($view_post->currentPage()+1) }}"> Next 
                  <i class="fa fa-angle-right pl-1"></i>
                </a>
              </li>
            </ul>
          @endif
        </nav>
      </div>
    </div>
  </div>
</section>

答案 19 :(得分:0)

这是定制的Laravel分页的简单解决方案,其中包括服务器和客户端代码。

假设使用Laravel 5.2和以下包含的视图:

@include('pagination.default',['pager'=> $ data])

功能

  • 显示“上一个”和“下一个”按钮,并在不适用时将其禁用。
  • 显示第一页和最后一页按钮。
  • 示例:(上一页|第一| ... | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | ... |最后|下一个)

default.blade.php

@if ($paginator->last_page > 1)
<ul class="pagination pg-blue">
    <li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
        <a class="page-link" tabindex="-1" href="{{ '/locate-vendor/'}}{{ substr($paginator->prev_page_url,7) }}">
            Previous
        </a>
    </li>

    <li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
        <a class="page-link" tabindex="-1" href="{{ '/locate-vendor/1'}}">
            First
        </a>
    </li>

    @if ( $paginator->current_page > 5 )
    <li class="page-item">
        <a class="page-link" tabindex="-1">...</a>
    </li>
    @endif

    @for ($i = 1; $i <= $paginator->last_page; $i++)
        @if ( ($i > ($paginator->current_page - 5)) && ($i < ($paginator->current_page + 5)) )
        <li class="page-item {{($paginator->current_page == $i)?'active':''}}">
            <a class="page-link" href="{{'/locate-vendor/'}}{{$i}}">{{$i}}</a>
        </li>
        @endif
    @endfor

    @if ( $paginator->current_page < ($paginator->last_page - 4) )
    <li class="page-item">
        <a class="page-link" tabindex="-1">...</a>
    </li>
    @endif

    <li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
        <a class="page-link" href="{{'/locate-vendor/'}}{{$paginator->last_page}}">
            Last
        </a>
    </li>

    <li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
        <a class="page-link" href="{{'/locate-vendor/'}}{{substr($paginator->next_page_url,7)}}">
            Next
        </a>
    </li>
</ul>
@endif

服务器端控制器功能

public function getVendors (Request $request)
    {
        $inputs = $request->except('token');
        $perPage  = (isset($inputs['per_page']) && $inputs['per_page']>0)?$inputs['per_page']:$this->perPage;   
        $currentPage = (isset($inputs['page']) && $inputs['page']>0)?$inputs['page']:$this->page;   
        $slice_init = ($currentPage == 1)?0:(($currentPage*$perPage)-$perPage);

        $totalVendors = DB::table('client_broker')
                           ->whereIn('client_broker_type_id', [1, 2])
                           ->where('status_id', '1')
                           ->whereNotNull('client_broker_company_name')
                           ->whereNotNull('client_broker_email')
                           ->select('client_broker_id', 'client_broker_company_name','client_broker_email')
                           ->distinct()
                           ->count();

        $vendors = DB::table('client_broker')
                           ->whereIn('client_broker_type_id', [1, 2])
                           ->where('status_id', '1')
                           ->whereNotNull('client_broker_company_name')
                           ->whereNotNull('client_broker_email')
                           ->select('client_broker_id', 'client_broker_company_name','client_broker_email')
                           ->distinct()
                           ->skip($slice_init)
                           ->take($perPage)
                           ->get();

        $vendors = new LengthAwarePaginator($vendors, $totalVendors, $perPage, $currentPage);

        if ($totalVendors) {
            $response = ['status' => 1, 'totalVendors' => $totalVendors, 'pageLimit'=>$perPage, 'data' => $vendors,  'Message' => 'Vendors Details Found.'];
        } else {
            $response = ['status' => 0, 'totalVendors' => 0, 'data' => [], 'pageLimit'=>'',  'Message' => 'Vendors Details not Found.'];
        }
        return response()->json($response, 200);

    }