Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Use variables of model in model factories

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(),
    ];
});
like image 785
manniL Avatar asked Dec 07 '16 22:12

manniL


2 Answers

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(),
    ];
});
like image 176
jackel414 Avatar answered Nov 02 '22 07:11

jackel414


Have you tried

$name ="Something here";

factory(App\Post::class)->create(["name" => $name, "slug" => str_slug($name)]);
like image 29
pseudoanime Avatar answered Nov 02 '22 05:11

pseudoanime