簡體   English   中英

Laravel 錯誤:數組到字符串的轉換

[英]Laravel error : Array to string conversion

我想 select 並從我的表單中存儲多個數據,輸入名稱為“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();
        
    });
}

我的 model:

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',
        ],

我需要幫助 !

像這樣在 model 中修復您的訪問器和突變器。 這些函數區分大小寫

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。

在 laravel 中使用casts表。 鑄造在 laravel

將此添加到Project model 中:

protected $casts = [
        'property_type' => 'array',
    ];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM