phpMick's avatar
Level 15

ID of model created with model factory.

Hi,

Laravel 5.3

I am trying to do this:

        $article = factory(Article::class)->make();

        $response = $this->call('POST', '/articles/action/' .$article->id, ['_token' => csrf_token()]);

I just want to create a model, then perform an action on it.

The $article doesn't have an id. I expected it to have one. How else can I do this?

Mick

ModelFactory.php

$factory->define(App\Models\Article::class, function (Faker\Generator $faker) {

    return [
        'actioned' => 0,
        'headline' => $faker->sentence($nbWords = 6, $variableNbWords = true),
        'URL' => $faker->url

    ];
});

0 likes
3 replies
martinbean's avatar
Level 80

@phpMick The make() method just instantiates a model instance, it doesn’t persist it to the database. You’ll want to use create() for that:

$article = factory(Article::class)->create();

$id = $article->id;
2 likes
phpMick's avatar
Level 15

Cheers @martinbean .

Day 2 of TDD and I'm determined not to give up this time!

Any resources you can suggest?

Mick

Please or to participate in this conversation.