Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to database seed JSON field in Laravel?

Tags:

json

php

laravel

I am having trouble to seed user_preference column from users table which is of JSON type. I get error 'Array to string conversion' in my git bash when I type php artisan db:seed.

UserSeeder.php

public function run()
{
    $faker = Faker\Factory::create();
    foreach ($this->getUsers() as $userObject) {
        $user = DB::table('users')->insertGetId([
            "first_name" => $userObject->first_name,
            "last_name" => $userObject->last_name,
            "email" => $userObject->email,
            "email_verified_at" => Carbon::now(),
            "password" => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
            "city" => 'Beograd',

            'user_preferences' => [
                $faker->randomElement(["house", "flat", "apartment", "room", "shop", "lot", "garage"])
            ],

            "created_at" => Carbon::now(),
            "updated_at" => Carbon::now(),
            "type" => 'personal',
        ]);
}

Users Table

Schema::table('users', function (Blueprint $table) {
    $table->json('user_preferences')->nullable()->after('city');
});

User Model

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use EntrustUserTrait;

    protected $fillable = [
        'first_name', 'last_name', 'email', 'password',
        'city', 'user_preferences', 'active', 'type'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'user_preferences' => 'array',
    ];
}
like image 427
mrmar Avatar asked Jul 26 '19 11:07

mrmar


2 Answers

You forgot to encode it to json. So you are trying to insert an Array. It tries to serialize the array to a string, which doesn't work.

'user_preferences' => json_encode([
     $faker->randomElement(
          [
            "house",
            "flat", 
            "apartment", 
            "room", "shop", 
            "lot", "garage"
          ]
       )
  ]),
like image 191
Kerel Avatar answered Oct 23 '22 03:10

Kerel


In Laravel 8, you can just use it like this:

'user_preferences' => [
   $faker->randomElement(
      [
        'house',
        'flat', 
        'apartment', 
        'room', 'shop', 
        'lot', 'garage'
      ]
   )
],

Note: no need to json_encode it.

Of course dont forget to put this inside your model.

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'user_preferences' => 'array'
];
like image 5
berusjamban Avatar answered Oct 23 '22 01:10

berusjamban