我有一个自定义视图,在某些功能中,我使用了
paginate
,而其他功能我不使用paginate
。现在我如何检查我是否使用了paginate
?
@if($products->links())
{{$products->links()}}
@endif // not work
当然,我知道我可以使用变量作为 true false 来检查它,但是有没有任何本机函数来检查它?
这非常有效。检查
$products
是否是 Illuminate\Pagination\LengthAwarePaginator
的实例,然后显示分页链接。
@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{$products->links()}}
@endif
@if($threads->hasPages())
{{ $threads->links() }}
@endif
简单的一个!
尝试这样
@if($products instanceof \Illuminate\Pagination\AbstractPaginator)
{{$products->links()}}
@endif
您需要检查
$products
是否是 Illuminate\Pagination\AbstractPaginator
的实例。它可以是一个数组,也可以是 Laravel 的 Collection
。
从 Laravel 7 开始,你现在可以这样做:
@if( $vehicles->hasPages() )
{{ $vehicles->links() }}
@endif
不要对变量的基类进行检查。这可能会导致在未来的 Laravel 版本中更改基类时出现问题。只需检查方法链接是否存在:
@if(method_exists($products, 'links'))
{{ $products->links() }}
@endif
另一种方式:
@if (class_basename($products) !== 'Collection')
{{ $products->links() }}
@endif
您可以使用 PHP 函数:get_class($products) - 获取完整的类名。 Laravel 应该有一些函数来检查 ->paginate() 是否正在使用。
paginate(0)
而不是 get()
{{$products->links}}
。不需要@if @endif
。laravel 分页有 2 种类型:
基于以上条件,你可以尝试这个解决方案:
@if(
$products instanceof \Illuminate\Pagination\Paginator ||
$products instanceof Illuminate\Pagination\LengthAwarePaginator
)
{{ $products->links() }}
@endif
如果你使用$products->paginate();在控制器中,视图中始终会有一个 \Illuminate\Pagination\LengthAwarePaginator 的实例。
如果你想检查分页是否实际使用:
@if($products->previousPageUrl() || $products->nextPageUrl())
{{ $products->links() }}
@endif
更正代码(添加“isset”):
@if(isset($products->links()))
{{$products->links()}}
@endif
较短版本:
{{$products->links() ?? ''}}
它适用于分页、简单分页以及没有分页时。使用“$products->hasMorePages()”的解决方案将不会在最后一页显示分页链接。
请使用以下格式
@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{$products->links()}}
@endif
@if($products->currentPage() > 1)
{{$products->links()}}
@endif
检查产品是否是 Pagination 的实例
@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator)
{{ $products->links() }}
@endif