简体   繁体   中英

Laravel error : Array to string conversion

i want to select and store multiple data from my form the input name is "property_type", but i get that error 'Array to string conversion ': this is my migration:

 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();
        
    });
}

my 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);
}

the view:

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

my storeprojectrequest:

'property_type' => [
            'array',
            'nullable',
        ],

i need help !

Fix your Accessors and Mutators like this in Your model. these functions are case sensitive

public function getPropertyTypeAttribute($value)
{
    return json_decode($value);
}

public function setPropertyTypeAttribute($value)
{
    $this->attributes['property_type'] = json_encode($value);
}

if you're using Laravel 8.77 or later also you can use them like below.

use Illuminate\Database\Eloquent\Casts\Attribute;

protected function propertyType(): Attribute
{
    return new Attribute(
        fn($value) => json_decode($value),
        fn($value) => json_encode($value)
    );
}

the first parameter is the getter and the second one is the setter.

Use casts in laravel. casts in laravel

Add this to the Project model:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM