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',
];
}
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"
]
)
]),
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'
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With