2

I have an error on Laravel 9 when run seeder, its say Array to string conversion

I have a same seeder type json before this DataMaster table, and its working. But when i run DataMasterSeeder, its not working

My seeder:

<?php

namespace Database\Seeders;

use App\Models\DataMaster;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DataMasterSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //SDU
        DataMaster::create(['formId' => 1, 'userId' => 1, 'kecamatanId' => 1, 'desaId' => null, 'fieldDatas' => [['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']], 'level' => 'kecamatan']);
    }
}

And my DataMaster migration:

public function up()
    {
        Schema::create('data_masters', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('formId');
            $table->unsignedBigInteger('userId');
            $table->unsignedBigInteger('kecamatanId')->nullable();
            $table->unsignedBigInteger('desaId')->nullable();
            $table->json('fieldDatas');
            $table->enum('level', ['kecamatan', 'desa']);
            $table->timestamps();

            $table->foreign("formId")->references("id")->on("forms")->onDelete('cascade');
            $table->foreign("userId")->references("id")->on("users")->onDelete('cascade');
            $table->foreign("kecamatanId")->references("id")->on("kecamatans")->onDelete('cascade');
            $table->foreign("desaId")->references("id")->on("desas")->onDelete('cascade');
        });
    }

I have another seeder like fieldDatas json field in this DataMaster seeder, and i run it successfully before run DataMaster seeder.

1 Answer 1

3

you should encode the field fieldDatas before inserting

DataMaster::create([
    'formId' => 1,
    'userId' => 1,
    'kecamatanId' => 1,
    'desaId' => null,
    // here...
    'fieldDatas' => json_encode([['id' => '1', 'name' => 'jumlah', 'title' => 'Jumlah', 'value' => '4605']]),
    'level' => 'kecamatan',
]);
Sign up to request clarification or add additional context in comments.

2 Comments

thank you sir, its work now. But i wonder in other seeder i do like that, dont use json_encode, and its still work. 'fields' => [[ 'id' => 1, 'name' => 'jumlah', 'title' => 'Jumlah', ]],
there may be a caster in the model, the caster will cast the data before the insertion laravel.com/docs/9.x/eloquent-mutators#attribute-casting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.