Basharmal
Basharmal

Reputation: 1384

Data truncated - $faker->randomElements

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?

Upvotes: 0

Views: 2035

Answers (2)

Digvijay
Digvijay

Reputation: 8947

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)

Upvotes: 1

Lucas Pace
Lucas Pace

Reputation: 277

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'

Upvotes: 0

Related Questions