Seeding Poll data

Step 01: running artisan command to create poll factory, seeder, migration and model files

php artisan make:model Poll -mfs 


Step 02:
Setting up PollFactory.php


namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Poll>
 */
class PollFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array mixed>
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name
        ];
    }
}


Step 03:
Setting up PollSeeder.php


namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class PollSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\Poll::factory(10)->create();        
    }
}


Step 04:
Setting up poll migration file

public function up()
{
	Schema::create('polls', function (Blueprint $table) {
		$table->id();
		$table->string('title', 100);
		$table->timestamps();
	});
} 


Step 05:
Setting up modal Poll.php


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Poll extends Model
{
    use HasFactory;

    protected $fillable = ['title'];
}


Step 06:
Setting up DatabaseSeeder.php

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            PollSeeder::class
        ]);
    }
}


Step 07:
Running artisan command for seeding of poll data

php artisan migrate --seed

Related Posts


Building RESTful APIs in Laravel

Seeding Question data for a poll

Pagination for poll in restful api

Uploading image in restful api