Laravel更改分页数据

时间:2016-05-08 17:38:22

标签: laravel

我的Laravel分页输出就像以前的laravel分页一样,但是我需要为每个对象更改数据数组。 我的输出是:

Output

如您所见,数据对象有2个项目,我需要更改。

我的代码是:

$items = $this->items()
        ->where('position', '=', null)
        ->paginate(15);

返回带有数据透视表的用户项目,但我不喜欢数据透视表在JSON中的显示方式,所以我决定更改项目,并在项目之前用枢轴组织每个项目。 / p>

为此,我尝试使用foreach

foreach ($items->data as $item)
        {

        }

这给我一个错误,原因我不知道:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$data"
status_code: 500

任何帮助?

12 个答案:

答案 0 :(得分:49)

paginator的项目是一个集合。您可以抓住它并转换数据,如下所示:

$paginator = $this->items()->where('position', '=', null)->paginate(15);
$paginator->getCollection()->transform(function ($value) {
    // Your code here

    return $value;
})

答案 1 :(得分:10)

如果您想保留分页的项目:

    $itemsPaginated = $this->items()
         ->paginate(15);

    $itemsTransformed = $itemsPaginated
        ->getCollection()
        ->map(function($item) {
            return [
                'id' => $item->id,
            ];
    })->toArray();

    $itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
        $itemsTransformed,
        $itemsPaginated->total(),
        $itemsPaginated->perPage(),
        $itemsPaginated->currentPage(), [
            'path' => \Request::url(),
            'query' => [
                'page' => $itemsPaginated->currentPage()
            ]
        ]
    );

答案 2 :(得分:2)

如果要更改或更新Laravel分页输出,但不影响分页,则应遵循以下说明。

$items = Model::paginate(10);

$updatedItems = $items->getCollection();

// data manipulation

// ...

$items->setCollection($updateItems);

您可以从here

进行检查

答案 3 :(得分:1)

我可以做的更短一些。这将返回编辑后的$array而不是简单的$paginated。本示例修改文件名。 doc对我有用。

    $paginated=$query->paginate(12);
    $array=$paginated->toArray();
    foreach ($array['data'] as $r=>$record) {
        $array['data'][$r]->gif=$array['data'][$r]->gif.".gif";
    }
    return $array;

答案 4 :(得分:0)

-Laravel 5.4

// example update column "photo" 
// from "/path/to/photo.png" 
// to "abc.com/path/to/photo.png"
foreach ($items as $item)
{
    $path = $item->photo;

  // Remove 
  $item->offsetUnset("photo");

  // Set
  $item->offsetSet("photo", url($path));
}

答案 5 :(得分:0)

我遇到了同样的问题 然后我发现了Eloquent mutators

它们允许您在获取或设置数据时修改数据。

在我的示例中,我将HTML存储为Markdown,然后以HTML格式检索它 你已经在你的问题中包含了很少的代码,所以我将为我的特定事件提供我自己的版本。此外,mutator代码放在模型中,而不是控制器。

use Illuminate\Mail\Markdown;
use Facades\League\HTMLToMarkdown\HtmlConverter as Markup;

class Post extends Model
{
    protected $fillable = [
        'title', 'body'
    ];

    /**
     * Convert to HTML when displaying on the screen.
     */
    public function getBodyAttribute($value)
    {
        return $this->attributes['body'] = Markdown::parse($value);
    }

    /**
     * Convert to Markdown when storing in the database.
     */
    public function setBodyAttribute($value)
    {
        return $this->attributes['body'] = Markup::convert($value);
    }
}

函数名称必须符合以下条件:

  1. 以小写字母getset开头。
  2. 必须是PascalCase中的数据库列(或者Laravel引用它的StudlyCase;虽然我认为命名不正确。请参见此处:https://stackoverflow.com/a/32731818/3578036)。
  3. 最后,函数名称必须以Attribute结尾,并带有大写A

答案 6 :(得分:0)

getCollection

是获取物品的一种方法。另一种方法是使用这个 例如,user没有name参数,只有first_namelast_name

$userPaginatedData = User::paginate(15);
$users = $userPaginatedData->items();

foreach($users as $user) {
   $user->name = $user->first_name . ' ' . $user->last_name;
}


return $userPaginatedData;

现在,在data键中,您将看到每个user都具有name参数。

答案 7 :(得分:0)

示例:

ansible-playbook -i \
            ../../inventories/packtclusters/ \
            -e "worker_iam_role_arn=$(terraform output worker_iam_role_arn) \
                cluster_name=$(terraform output cluster_full_name) \
                aws_default_region=$(terraform output aws_region)" \
            ../../cluster.yaml -vvv

ansible-playbook 2.10.6
  config file = None
  configured module search path = ['/Users/skliarm/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
  executable location = /usr/local/bin/ansible-playbook
  python version = 3.9.2 (default, Feb 24 2021, 13:26:09) [Clang 12.0.0 (clang-1200.0.32.29)]
No config file found; using defaults
host_list declined parsing /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/inventories/packtclusters/hosts as it did not pass its verify_file() method
script declined parsing /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/inventories/packtclusters/hosts as it did not pass its verify_file() method
auto declined parsing /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/inventories/packtclusters/hosts as it did not pass its verify_file() method
Parsed /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/inventories/packtclusters/hosts inventory source with ini plugin
statically imported: /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/tasks/aws-auth.yaml
redirecting (type: modules) ansible.builtin.k8s to community.kubernetes.k8s
statically imported: /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/tasks/namespaces.yaml
redirecting (type: modules) ansible.builtin.k8s to community.kubernetes.k8s
Skipping callback 'default', as we already have a stdout callback.
Skipping callback 'minimal', as we already have a stdout callback.
Skipping callback 'oneline', as we already have a stdout callback.

PLAYBOOK: cluster.yaml *********************************************************
1 plays in ../../cluster.yaml

PLAY [deploy k8s add-ons] ******************************************************
META: ran handlers

TASK [deploy aws auth configmap] ***********************************************
task path: /Users/skliarm/git/kubernetes/Kubernetes-in-Production-Best-Practices/Chapter04/ansible/tasks/aws-auth.yaml:1
The full traceback is:
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/ansible/executor/task_executor.py", line 116, in run
    items = self._get_loop_items()
  File "/usr/local/lib/python3.9/site-packages/ansible/executor/task_executor.py", line 250, in _get_loop_items
    items = templar.template(self._task.loop)
  File "/usr/local/lib/python3.9/site-packages/ansible/template/__init__.py", line 822, in template
    return [self.template(
  File "/usr/local/lib/python3.9/site-packages/ansible/template/__init__.py", line 822, in <listcomp>
    return [self.template(
  File "/usr/local/lib/python3.9/site-packages/ansible/template/__init__.py", line 789, in template
    result = self.do_template(
  File "/usr/local/lib/python3.9/site-packages/ansible/template/__init__.py", line 1057, in do_template
    res = j2_concat(rf)
  File "<template>", line 15, in root
  File "/usr/local/lib/python3.9/site-packages/ansible/template/__init__.py", line 257, in wrapper
    return list(ret)
  File "/usr/local/lib/python3.9/site-packages/yaml/__init__.py", line 127, in load_all
    loader = Loader(stream)
  File "/usr/local/lib/python3.9/site-packages/yaml/loader.py", line 34, in __init__
    Reader.__init__(self, stream)
  File "/usr/local/lib/python3.9/site-packages/yaml/reader.py", line 74, in __init__
    self.check_printable(stream)
  File "/usr/local/lib/python3.9/site-packages/yaml/reader.py", line 143, in check_printable
    raise ReaderError(self.name, position, ord(character),
yaml.reader.ReaderError: unacceptable character #x001b: special characters are not allowed
  in "<unicode string>", position 281
fatal: [localhost]: FAILED! => {
    "msg": "Unexpected failure during module execution.",
    "stdout": ""
}

PLAY RECAP *********************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0  
<块引用>

注意 $models->setCollection(collect($franchiseData));你必须使用 collect() 否则你会得到错误。

答案 8 :(得分:-1)

事实上,$items是一个Paginator个实例,您可以将其删除:

foreach ($items as $item)
{

}

应该有用。

答案 9 :(得分:-1)

<?php 

$itemsPaginated = $this->items()->paginate(15);

$itemsPaginated = json_encode($itemsPaginated);

foreach ($itemsPaginated->data as $key => $item) {
    $results->data[$key]; //Modify
}

$itemsPaginated = json_encode($results);

答案 10 :(得分:-3)

忽略laravel中的分页并击中正常数据

foreach ($items as $item)
{

}

答案 11 :(得分:-4)

您必须在刀片中使用以下代码

{!! $items->render() !!}