I am trying to create some dummy data to testunit my appication in Laravel 5.7. I am using a factory to create:
All in one.
My factory looks like this:
$factory->define(App\Profile::class, function (Faker $faker) {
$profile = Profile::create([
'title' => $faker->userName,
'gender_id' => 0,
'role_id' => 1,
'slug' => str_slug($faker->userName),
]);
for ($i=0; $i < 5; $i++) {
$event = Event::create([
'profile_id' => $profile->id,
'title' => $faker->sentence,
'subtitle' => $faker->sentence,
'slug' => str_slug($faker->sentence),
'category_id' => 1,
'language_id' => 1,
'video_url' => 'video',
'description' => $faker->paragraph,
]);
for ($i=0; $i < 10; $i++) {
$eventcomment = Eventcomment::create([
'profile_id' => $profile->id,
'event_id' => $event->id,
'body' => $faker->paragraph,
]);
}
}
return $profile;
});
But when I run it in Tinker like this:
php artisan tinker
>>>factory('App\Profile', 20)->create();
I get the following error:
PHP Recoverable fatal error: Object of class Closure could not be converted to string in C:/laragon/www/definitive/vendor/laravel/framework/src/Illuminate/Support/Str.php on line 338
Any idea how to solve this problem?
If you want to customize any string, it should be outside of create method.
$factory->define(App\Profile::class, function (Faker $faker) {
$slugName = str_slug($faker->userName);
$profile = Profile::create([
'title' => $faker->userName,
'gender_id' => 0,
'role_id' => 1,
'slug' => $slugName,
]);
$slugSentence = str_slug($faker->sentence);
$profileId = $profile->id;
for ($i=0; $i < 5; $i++) {
$event = Event::create([
'profile_id' => $profileId,
'title' => $faker->sentence,
'subtitle' => $faker->sentence,
'slug' => $slugSentence,
'category_id' => 1,
'language_id' => 1,
'video_url' => 'video',
'description' => $faker->paragraph,
]);
$eventId = $event->id;
for ($i=0; $i < 10; $i++) {
$eventcomment = Eventcomment::create([
'profile_id' => $profileId,
'event_id' => $eventId,
'body' => $faker->paragraph,
]);
}
}
return $profile;
});
Or You can use Closure attributes