开始使用 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);
}
所以整个问题不应该显示为字符串,实际上我找不到解决方案。
答案 0 :(得分:3)
您需要将 attribute casting 添加到您的模型中,它会将其保存为数据库中的 json 字符串,并在调用时对其进行 json 解码。
class User extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'profile' => 'array',
];
}