Laravel 8 追加 JSON 值

2021-07-19 11:48 更新

有時(shí),需要在數(shù)組或 JSON 中添加一些數(shù)據(jù)庫中不存在字段的對應(yīng)屬性。要實(shí)現(xiàn)這個(gè)功能,首先要定義一個(gè) 修改器。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the administrator flag for the user.
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] === 'yes';
    }
} 

然后,在模型屬性 appends 中添加該屬性名。注意,盡管訪問器使用「駝峰命名法」方式定義,但是屬性名通常以「蛇形命名法」的方式來引用:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_admin'];
} 

使用 append 方法追加屬性后,它將包含在模型的數(shù)組和 JSON 中。appends 數(shù)組中的屬性也將遵循模型上配置的 visiblehidden 設(shè)置。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號