Laravel Database Seeder using insert multiple records
Today, we will tell you about the Laravel Database Seeder. Laravel is a PHP framework. it provides many facilities such as Database Seeder. let’s see that taking about the laravel Database Seeder.
Database seeder means if you want to insert multiple records or some dummy data in the database it is called database seeder.
Step 1: Install Laravel and setting the database configuration.
You can follow our below article URL for this step.
Step 2: Create Table using migration
Now, We need to create a migration. so we will below command using create the students table migration.
1 | php artisan make:migration create_students_table --create=students |
After complete migration. we need below changes in the database/migrations/create_students_table file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('students', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('first_name'); $table->string('last_name'); $table->text('address'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } } ?> |
Run the below command. after the changes above file.
1 | php artisan migrate |
Step3: Create the Model.
we create a student model using the below command.
1 | php artisan make:model Student |
Step4: Create the seeder class
we will create StudentsTableSeeder class using the below command.
1 | php artisan make:seed StudentsTableSeeder |
Now, open the file StudentsTableSeeder.php at the database/seeds directory and replace the below content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php use Illuminate\Database\Seeder; use App\Student; class StudentsTableSeeder extends Seeder { public function run() { for ($i=0; $i < 6; $i++) { Student::create([ 'first_name' => str_random(10), 'last_name' => str_random(10), 'address' => str_random(25) ]); } } } ?> |
When we complete the changes, then we have to need to edit the database/seeds/DatabaseSeeder.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call([ UsersTableSeeder::class, StudentsTableSeeder::class, ]); } } ?> |
Now, when we will execute the below command then DatabaseSeeder class is called and it will insert the records into the database.
1 | php artisan db:seed |