LaVOZs

The World’s Largest Online Community for Developers

'; laravel - Data truncated - $faker->randomElements - LavOzs.Com

I created a factory and want to generate randomElements from an array. However, when I run the factory in tinker I get "Array to string conversion error". Can someone explain why?

This is the column in the table

$table->enum('interest_tags', ['php', 'javascript', 'vue']);

And I generate randomElements from the array like this:

'interest_tags' => $faker->randomElements(['php', 'javascript', 'vue'], 2),

Am I doing something wrong here?

You can store the data in comma separated format in your DB.

'interest_tags' => implode(",", $faker->randomElements(['php', 'javascript', 'vue'], 2))

In your Model::class you can create an accessor like

public function getInterestTagsAttribute($value)
{
    return explode(",", $value); // php,vue  -->  ['php', 'vue']
}


Or if you planning to store just one item then use randomElement()

 @method mixed randomElement(array $array = array('a', 'b', 'c'))
 @method array randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)

randomElements function returns a array. He size is the second parameter. In your case the return its something like:

['php','vue]

But you cant store a array in database. You only can store a string. See randomElement method, he return a only one element, like:

'php'
Related
Seeding With TestDummy and Faker
Laravel 5/Faker - Factory data changes
Creating Seeder with foreign key field Laravel 5.3
Laravel: Seeding multiple unique columns with Faker
laravel seeder array to string conversion
Seeding a test database in Laravel using factories and a deterministic seed
Laravel: seeding a nested set table with Faker
PHP Notice: Array to string conversion; Database Factories
ErrorException : implode(): Passing glue string after array is deprecated. Swap the parameters