php - 在 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);
}
所以他们不应该显示为字符串的整个问题实际上我找不到解决方案。
解决方案
您需要将属性转换添加到模型中,它会将其保存为数据库中的 json 字符串,并在调用时对其进行 json 解码。
class User extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'profile' => 'array',
];
}
推荐阅读
- python - 烧瓶:“str”对象没有属性“is_active”
- reactjs - 使用 BrowserRouter 对路由更改进行调度操作
- .net - 使用 Prometheus 测量 .NET 应用程序的传出 HTTP 请求
- jquery - Laravel 5.8 JSON 响应与如此多的空格
- javascript - 从数组中删除所有重复的元素
- javascript - 如何添加文件大小验证
- java - 将 GenericRecords 的 pCollection 写入 Parquet 文件的数据流
- python - Curve_Fit 的结果关闭
- javascript - JavaScript 仅在带中断的调试模式下工作
- javascript - 无法从文本文件返回值