Okay, let's say that I have a Post model with the attributes name
, slug
and content
. I'd like to generate models with my ModelFactory, but want to set a specific name, which I do by overwriting the value:
factory(App\Post::class)->create(["name" => "Something here"]);
But now I want the slug to auto-generate by using the (new) name and without passing it as argument. Like
"slug" => str_slug($name);
Is this possible or do I need to write the slug manually?
When using the factory below with ->create(['name' => 'anything']);
the slug is not created.
$factory->define(App\Post::class, function (Faker\Generator $faker) {
static $name;
return [
'name' => $faker->name,
'slug' => $name ?: str_slug($name),
'content' => $faker->sentences(),
];
});
This should do the trick. You can pass a name in manually or let Faker handle it.
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'slug' => function (array $post) {
return str_slug($post['name']);
},
'content' => $faker->sentences(),
];
});
Have you tried
$name ="Something here";
factory(App\Post::class)->create(["name" => $name, "slug" => str_slug($name)]);
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