Search code examples
laraveltinker

Laravel 8 + Tinker: How to create dummy data


In previous Laravel version I use this in tinker:

php artisan tinker
factory(App\Banana::class, 3)->create();

But in Laravel 8, it gives this error: `PHP Error: Class 'Database/Factories/bananaFactory' not found

How to create dummy data in Laravel 8 using tinker please? Thank you.


Solution

  • You can try by this steps:

    1. Inside your Banana Model added HasFactory like below:
    <?php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    
    class Banana extends Model
    {
        use HasFactory;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'title', 'description'
        ];
    }
    
    
    1. Create Factory
    - php artisan make:factory BananaFactory --model=Banana
    
    1. After generate BananaFactory go to that path then:
    <?php
     
    namespace Database\Factories;
     
    use App\Models\Post;
    use Illuminate\Database\Eloquent\Factories\Factory;
    use Illuminate\Support\Str;
     
    class BananaFactory extends Factory
    {
        /**
         * The name of the factory's corresponding model.
         *
         * @var string
         */
        protected $model = Banana::class;
     
        /**
         * Define the model's default state.
         *
         * @return array
         */
        public function definition()
        {
            return [
                'title' => $this->faker->title,
                'description' => $this->faker->text,
            ];
        }
    }
    
    
    1. After that run this command:
     composer dump-autoload
    
    1. then open the terminal and run:
    php artisan tinker
    Banana::factory()->count(3)->create()
    

    Important: Here is document that related to create factory:

    https://laravel.com/docs/8.x/database-testing#creating-factories