首页 > 解决方案 > 在 PUT 请求对象属性显示为字符串之后

问题描述

开始使用 Laravel 8 并且有点挣扎于 PUT 请求。每当我尝试更新(在更新时创建实际的新字段)具有新属性的用户时,它们都会显示为字符串。

这是我的用户迁移

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('username');
        $table->string('password');
        $table->string('type')->nullable();
        $table->string('profile')->nullable();
        $table->timestamps();
    });
}

这是我的控制器功能

  public function update(Request $request, $id)
    {
        $user = User::find($id);

        $user->update([
            'profile' => [
                'company_name' => $request->input('company_name'),
                'company_vat' => $request->input('company_vat'),
            ],
        ]);

        return response($user, 201);
    }

这是在执行 put 请求后从 get 请求中看到的样子。要求

所以他们不应该显示为字符串的整个问题实际上我找不到解决方案。

标签: phplaravel

解决方案


您需要将属性转换添加到模型中,它会将其保存为数据库中的 json 字符串,并在调用时对其进行 json 解码。

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'profile' => 'array',
    ];
}

推荐阅读