Laravel 在模型上定义一个带值的默认键

Laravel define a default key with value on Model

在我的 Laravel 8 项目中,我有一个名为 Campaign 的模型,但我的前端是在 Vue JS 中构建的,因此需要在 Campaign 上有一些键用于上下文目的,例如打开并在遍历元素时关闭下拉菜单,数据库列对此不是必需的。

我想在我的 Campaign 模型中添加一些默认的 key/value 对,例如:dropdown_is_open 并且应该有一个默认值 false.

我遇到了一个模型的 default attributes 并尝试添加它但是在对象上看不到我的新密钥,我错过了什么?

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Campaign extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * Indicates if the model's ID is auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;

    /**
    * The table associated with the model.
    *
    * @var string
    */
    protected $table = 'campaigns';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'campaign',
        'template'
    ];

    /**
     * The model's default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'dropdown_is_open' => false
    ];
}

控制器中的索引函数:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $campaigns = Campaign::where('user_id', Auth::id())
                         ->orderBy('created_at', 'desc')
                         ->get();

    if (!$campaigns) {
        return response()->json([
            'message' => "You have no campaigns"
        ], 404);
    }

    return response()->json([
        'campaigns' => $campaigns
    ], 200);
}

我希望看到:

{
  campaign: 'my campaign',
  template: '',
  dropdown_is_open: false <-- my key
}

之前我在索引函数中执行 foreach 并在每个项目上添加上下文键,但这只会显示索引函数,我必须在所有地方添加它。

希望下面的内容对您有所帮助。

Change it from my_custom_field to dropdown_is_open key (and from getMyCustomFieldAttribute to getDropdownIsOpenAttribute method-name).

自定义属性(或访问器)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model {
    protected $appends = ['my_custom_field'];

    public function getMyCustomFieldAttribute()
    {
        return false;
    }
}

The $appends in above is required only, to ensure that my_custom_field is preset/cached, and even sent as JSON-Response.