Laravel Method paginate不存在

时间:2018-01-08 10:33:09

标签: laravel methods pagination

我正在尝试对模型结果进行分页,但我得到“方法分页不存在。”。这是我的代码:

$user_dispatches = Dispatch::all()->where('user_id', Auth::id())->paginate(10);

我需要获取用户id等于当前经过身份验证的用户ID的所有记录。没有paginate()方法就可以正常工作。

6 个答案:

答案 0 :(得分:13)

您需要删除all()

Dispatch::where('user_id', Auth::id())->paginate(10);

当您使用all()时,您将从表中获取所有行并获取集合。然后你正在使用集合方法where()(而不是查询构建器方法where()),然后你试图在集合上使用paginate()方法,它不存在。

答案 1 :(得分:10)

延伸一点Alexey的完美答案:

  

Dispatch::all() =>返回Collection

     

Dispatch::all()->where() =>返回Collection

     

Dispatch::where() =>返回Query

     

Dispatch::where()->get() =>返回Collection

     

Dispatch::where()->get()->where() =>返回Collection

您只能在paginate上调用“Query”,而不能在Collection上调用。

是的,为whereQueries设置Collections功能并非常困惑,尽可能接近它们,但事实就是如此。

答案 2 :(得分:3)

要使用所有记录和分页,您需要使用以下代码:

$user_dispatches = Disspath::paginate(8);

答案 3 :(得分:1)

Dispatch::where('user_id', auth()->user()->id)->paginate(10);

答案 4 :(得分:1)

您需要删除方法all()

$user_dispatches = Dispatch::where('user_id', Auth::id())->paginate(10);

因为all()返回Collectionpaginate()使用了Builder

答案 5 :(得分:0)

您可以创建自己的自定义类:

<?php
namespace App\CustomClasses;

use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class ColectionPaginate
{
    public static function paginate(Collection $results, $pageSize)
    {
        $page = Paginator::resolveCurrentPage('page');
        
        $total = $results->count();

        return self::paginator($results->forPage($page, $pageSize), $total, $pageSize, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

    }

    /**
     * Create a new length-aware paginator instance.
     *
     * @param  \Illuminate\Support\Collection  $items
     * @param  int  $total
     * @param  int  $perPage
     * @param  int  $currentPage
     * @param  array  $options
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    protected static function paginator($items, $total, $perPage, $currentPage, $options)
    {
        return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
            'items', 'total', 'perPage', 'currentPage', 'options'
        ));
    }
}

然后使用它:

use App\CustomClasses\ColectionPaginate;
...
$result = $query->limit(100)->get();
$paginatedResult = ColectionPaginate::paginate($result, 10);
相关问题