【问题标题】:Error: Call to a member function paginate() on a non-object错误:在非对象上调用成员函数 paginate()
【发布时间】:2014-03-19 15:56:05
【问题描述】:

我正在尝试转换从 Eloquent 模型中检索为对象的一些数据,然后也使用 Laravel 的分页功能。但是,当我将数据转换为数组以对其进行转换时,我无法使用 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]);

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    试试看:

    $posts = Post::where('published', '=', true)->get()->toArray();
    
    $paginator = Paginator::make($posts, $totalItems, $perPage);
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多