Laravel 5 - Use variables of model in model factories

manniL

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.


My current factory

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    static $name;

    return [
        'name' => $faker->name,
        'slug' => $name ?: str_slug($name),
        'content' => $faker->sentences(),
    ];
});
jackel414

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(),
    ];
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related