Parth Vora
Parth Vora

Reputation: 4114

How to call a factory from a artisan command - Laravel

I want to call a factory function from a custom artisan command. But when I run that command, it doesn't run that factory function and it also not giving any error.

Here is custom artisan command:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Tag;

class CreateTags extends Command
{
    protected $signature = 'blog:create-tags';

    protected $description = 'To generate new random tags for blogs';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        factory(Tag::class, 5)->create();
    }
}

database/factories/Modelfactory.php:

$factory->define(App\Tag::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->word,
    ];
});

To fire that command from CLI:

php artisan blog:create-tags

However if I run that same factory using db:seed command, its working perfectly. Like

factories/seeds/TagsSeeder.php:

use Illuminate\Database\Seeder;
use App\Tag;
class TagsSeeder extends Seeder
{
    public function run()
    {
        Tag::truncate();
        factory(Tag::class, 5)->create();
    }
}

Let me know, if needs more info.

Upvotes: 3

Views: 6068

Answers (1)

Parth Vora
Parth Vora

Reputation: 4114

Sorry, it was my bad. I forgot to truncate the table, but in my mind I thought its there.

we can call a factory from a artisan command. There is nothing wrong in that.

    public function handle()
    {
        Tag::truncate();
        factory(Tag::class, 5)->create();
    }

Upvotes: 4

Related Questions