繁体   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