如何检查laravel中是否使用了分页

问题描述 投票:0回答:14

我有一个自定义视图,在某些功能中,我使用了

paginate
,而其他功能我不使用
paginate
。现在我如何检查我是否使用了
paginate

@if($products->links())

   {{$products->links()}}

@endif // not work 

当然,我知道我可以使用变量作为 true false 来检查它,但是有没有任何本机函数来检查它?

laravel laravel-5 pagination
14个回答
44
投票

这非常有效。检查

$products
是否是
Illuminate\Pagination\LengthAwarePaginator
的实例,然后显示分页链接。

@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )

   {{$products->links()}}

@endif

30
投票
@if($threads->hasPages())
  {{ $threads->links() }}
@endif

简单的一个!


9
投票

尝试这样

@if($products instanceof \Illuminate\Pagination\AbstractPaginator)

   {{$products->links()}}

@endif

您需要检查

$products
是否是
Illuminate\Pagination\AbstractPaginator
的实例。它可以是一个数组,也可以是 Laravel 的
Collection


7
投票

美丽的方式:

@if ($products->hasMorePages())
    {{ $products->links() }}
@endif

点击这里查看官方文档


7
投票

从 Laravel 7 开始,你现在可以这样做:

@if( $vehicles->hasPages() )
   {{ $vehicles->links() }}
@endif

5
投票

不要对变量的基类进行检查。这可能会导致在未来的 Laravel 版本中更改基类时出现问题。只需检查方法链接是否存在:

@if(method_exists($products, 'links'))
   {{ $products->links() }}
@endif

0
投票

另一种方式:

@if (class_basename($products) !== 'Collection')
   {{ $products->links() }}
@endif

您可以使用 PHP 函数:get_class($products) - 获取完整的类名。 Laravel 应该有一些函数来检查 ->paginate() 是否正在使用。


0
投票
  • 只需写
    paginate(0)
    而不是
    get()
  • 刀片模板:只需使用
    {{$products->links}}
    。不需要
    @if @endif

0
投票

laravel 分页有 2 种类型:

  • simplePaginate() 将返回 \Illuminate\Pagination\Paginator
  • paginate() 将返回 Illuminate\Pagination\LengthAwarePaginator

基于以上条件,你可以尝试这个解决方案:

@if(
    $products instanceof \Illuminate\Pagination\Paginator ||
    $products instanceof Illuminate\Pagination\LengthAwarePaginator
  )
 {{ $products->links() }}
@endif

0
投票

如果你使用$products->paginate();在控制器中,视图中始终会有一个 \Illuminate\Pagination\LengthAwarePaginator 的实例。

如果你想检查分页是否实际使用:

@if($products->previousPageUrl() || $products->nextPageUrl())

   {{ $products->links() }}

@endif

-1
投票

更正代码(添加“isset”):

@if(isset($products->links()))

   {{$products->links()}}

@endif

较短版本:

{{$products->links() ?? ''}}

它适用于分页、简单分页以及没有分页时。使用“$products->hasMorePages()”的解决方案将不会在最后一页显示分页链接。


-1
投票

请使用以下格式

@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )

   {{$products->links()}}

@endif                 

-1
投票
@if($products->currentPage() > 1)

   {{$products->links()}}

@endif

-1
投票

检查产品是否是 Pagination 的实例

@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator)
        {{ $products->links() }}
@endif
© www.soinside.com 2019 - 2024. All rights reserved.