如何将数组添加到laravel集合对象项

时间:2018-04-08 19:00:32

标签: php laravel

尝试将数组添加到对象上具有->push的laravel对象,但它无法正常工作。我看起来做错了什么?对象没有变化。

   $cottages = Cottage::all();

    foreach ($cottages as $cottage) {

        //returns array
        $gallery = $this->getCottageGallery($cottage['folder']);
        //should append to $cottage object
        $cottage->push($gallery);
    }

   dump($cottages);

2 个答案:

答案 0 :(得分:0)

我实际上只是使用$cottage->setAttribute('gallery', $gallery);将其分配给对象!

答案 1 :(得分:0)

你可以直接在集合中删除foreach语句:

$cottages = Cottage::all()->map(function ($cottage){
             $cottage->setAttribute('gallery', $this->getCottageGallery($cottage['folder']);

            return $cottage;
        });