【发布时间】:2022-01-25 10:18:51
【问题描述】:
我想从我的表单中选择并存储多个数据,输入名称是“property_type”,但我收到错误“数组到字符串转换”: 这是我的迁移:
public function up() {
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('ref')->nullable();
$table->string('name');
$table->string('community');
$table->text('property_type')->nullable();
$table->integer('floor_number')->nullable();
});
}
我的模型:
class Project extends Model implements HasMedia {
protected $fillable = [
'ref',
'name',
'community',
'property_type',
'floor_number',
];
public function setPtypeAttribute($value) {
$this->attributes['property_type'] = json_encode($value);
}
/**
* Get the categories
*
*/
public function getPtypeAttribute($value) {
return $this->attributes['property_type'] = json_decode($value);
}
观点:
<form enctype="multipart/form-data" method="POST" novalidate action="{{ route("admin.projects.store") }}" >
@csrf
<div class="form-group">
<label class="required">property_type</label>
<select class="form-control select2 name="property_type[]" id="property_type" required multiple="">
<option value="php">PHP</option>
<option value="react">React</option>
<option value="jquery">JQuery</option>
<option value="javascript">Javascript</option>
<option value="angular">Angular</option>
<option value="vue">Vue</option>
</select>
</div>
我的商店项目请求:
'property_type' => [
'array',
'nullable',
],
我需要帮助!
【问题讨论】:
-
访问者真的叫
getPtypeAttribute吗?不应该叫getPropertyTypeAttribute吗? (大小写也很重要) -
我改变了它,现在它存储在数据库中但是,在索引中我得到 json_decode() 期望参数 1 是字符串,给定数组(查看:C:\xampp\htdocs\OPEN- CRM-1\resources\views\admin\projects\index.blade.php)
-
如果您的 getter 和 mutator 正常工作,那么您只需要在其中使用
json_encode和json_decode而在代码中的其他地方不需要它们 -
是的,我没有在任何地方使用过,我只是在 getter 和 setter 中使用过!