我想從我的表單中選擇和存盤多個資料,輸入名稱是“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>
我的 storeprojectrequest :
'property_type' => [
'array',
'nullable',
],
我需要幫助 !
uj5u.com熱心網友回復:
在您的模型中像這樣修復您的訪問器和修改器。這些函式區分大小寫
public function getPropertyTypeAttribute($value)
{
return json_decode($value);
}
public function setPropertyTypeAttribute($value)
{
$this->attributes['property_type'] = json_encode($value);
}
如果您使用的是 Laravel 8.77 或更高版本,您也可以像下面那樣使用它們。
use Illuminate\Database\Eloquent\Casts\Attribute;
protected function propertyType(): Attribute
{
return new Attribute(
fn($value) => json_decode($value),
fn($value) => json_encode($value)
);
}
第一個引數是getter,第二個是setter。
uj5u.com熱心網友回復:
casts在 Laravel 中使用。在 Laravel 中強制轉換
將此添加到Project模型中:
protected $casts = [
'property_type' => 'array',
];
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394017.html
下一篇:如何使用js引數呼叫Php函式
