错误:在非对象上调用成员函数paginate()

时间:2014-03-19 15:56:06

标签: php laravel laravel-4

我正在尝试从Eloquent模型转换作为对象检索的一些数据,然后使用Laravel的paginate功能。但是,当我将数据转换为数组以进行转换时,我无法使用paginate方法。

$postsPerPage = 10;

$posts = Post::where('published', '=', true)->get();

$posts = Helpers::transform_posts($posts->toArray());

// $posts = Helpers::transform_posts($posts->toArray())->paginate($postsPerPage);
// doesn't work because $posts has been cast to an array
// error: Call to a member function paginate() on a non-object

return View::make('blog.index', ['posts' => $posts]);

班级助手:

public static function transform_post(array $post)
{
    $publishedDate = \Carbon\Carbon::createFromTimeStamp(strtotime($post['published_date']))->diffForHumans();

    return [
        'id' => $post['id'],
        'title' => $post['title'],
        'slug' => $post['slug'],
        'subtitle' => $post['subtitle'],
        'body' => $post['body'],
        'published' => (bool)$post['published'],
        'published_date' => $post['published_date'],
        'published_date_for_humans' => $publishedDate
    ];
}

public static function transform_posts(array $posts)
{
    foreach ($posts as &$array) {
        $array = Helpers::transform_post($array);
    }
    return $posts;
}

如何在不转换为数组的情况下执行此操作,以便仍然可以对数据使用paginate方法?

编辑:现在解决了这个问题:

    $posts = Post::where('published', '=', true)->get()->toArray();

    $posts = Helpers::transform_posts($posts);

    $posts = Paginator::make($posts, 0 , $postsPerPage);

    return View::make('blog.index', ['posts' => $posts]);

2 个答案:

答案 0 :(得分:3)

试一试:

$posts = Post::where('published', '=', true)->get()->toArray();

$paginator = Paginator::make($posts, $totalItems, $perPage);

答案 1 :(得分:0)

您是否尝试过分页而不首先将$ posts转换为数组?

$posts = Post::where('published', '=', true)->paginate($postsPerPage);