Laravel Collection helper put()问题

时间:2018-01-15 03:27:24

标签: php laravel-5.5

我需要一劳永逸地理解这一点。对不起,这是一个愚蠢的问题。

我有以下静态方法,它基本上为日期提供了idphp_format的表格。

当我获取数据时,我想在集合的每一行添加一列,以便它包含today格式的Carbon。我understood the put() helper就是这样做的。

我的方法:

public static function getWithSampleDates($type = null)
{
    if (! $type) {
        $dates = self::all();
    } else {
        $dates = self::where('type', '=', $type)->get();
    }

    foreach($dates as $date) {
        $date->put('label', Carbon::now()->format($date->php_format));
    }

    return $dates;
}

但这失败了:

BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::put()

我不明白。我认为$datescollection

1 个答案:

答案 0 :(得分:0)

答案是使用setAttribute(),尽管我仍然对使用put()感到困惑。

public static function getWithSampleDates($type = null)
{
    if (! $type) {
        $dates = self::get();
    } else {
        $dates = self::where('type', '=', $type)->get();
    }

    foreach($dates as $date) {
        $date->setAttribute('label', Carbon::now()->format($date->php_format));
    }

    return $dates;
}