Home > OS >  Laravel seeder column json
Laravel seeder column json

Time:11-17

I am creating a seeder in laravel, but I have to write 1 column json data, but I could not do it, how can I create a seeder column.

Seeder In seeder there will be "bank name" and "iban" in iban column

enter image description here Migration

    public function up()
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->id();
            $table->string('account_type');
            $table->string('name');
            $table->json('ibans')->nullable();
            $table->timestamps();
        });
    }

Seeder

    public function run()
    {
        DB::table('settings')->insert([
            'name' => 'Şirket Ünvanı',
            'account_type' => 'settings',
            'ibans' => json_decode('"a":1,"b":2',true),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

CodePudding user response:

It's

public function run()
    {
        DB::table('settings')->insert([
            'name' => 'Şirket Ünvanı',
            'account_type' => 'settings',
            'ibans' => json_encode(['bankname' => 1, 'iban' => '2', '0' => true]),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

enter image description here

CodePudding user response:

You can add this json field to your Model (Settings) as casting field (protected $cast). It will be automatically handles json_encode, -decode to an array.

protected $casts = [
    'ibans' => 'array'
];

$settings->ibans = $array; 
$array = $settings->ibans; 

https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting

  • Related