Laravel-9 Tutorial – How to Seed US States in Database using Laravel 9 Seeder

In this tutorial, we will teach you how to seed USA state names or records in MySQL using the Laravel database seeder class.

Laravel Seeder is a powerful yet helpful feature in the Laravel framework that let us populate the database with dummy or sample records or data for testing and web development purposes.

This is useful when you need to test your application with large amounts of data, and it helps to save time as you don’t have to enter the data manually.

A seeder class resides in Laravel; this PHP class helps extend the IlluminateDatabaseSeeder class and implements the run method. By using the run method’s help, you can smoothly use the DB class to seed US state records into your database.

We want you to have your utmost attention on the following conjugated steps relative to the Laravel us state seeder example.

Laravel 9 US State Database Seeder Example

  • Step 1: Download Laravel Framework
  • Step 2: Connect to Database
  • Step 3: Create Migration File
  • Step 4: Create Model File
  • Step 5: Build USA State Seeder
  • Step 6: Populate Database with USA States

Download Laravel Framework

There are two ways to set up the Laravel framework.

You can download the Laravel PHP framework by visiting the official website at https://laravel.com/ and clicking on the “Download” button.

You can go ahead and also download the latest version of Laravel through composer, which is a PHP package manager, by running the given command in your terminal or command prompt:

composer create-project laravel/laravel --prefer-dist laravel-blog

Once you have downloaded Laravel, you can move into the project directory using the given command.

cd laravel-blog

Connect to Database

To connect to a database in Laravel, you need to configure the database settings in the .env file.

You may find this file in the root of your Laravel project, and it includes environment-specific configuration settings, including the database connection details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Migration File

In Laravel, migrations are used to manage and adjust the database schema.

Migrations offer version control for your database schema, permitting you to change the database structure over time in a centralized environment.

php artisan make:migration create_usa_states_table

You have to add the given code into the database/migrations/xxx_create_usa_states_table.php file:


use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration
{
    
    public function up()
    {
        Schema::create('usa_states', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code');            
            $table->timestamps();
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('usa_states');
    }
};

Migrations are a way to manage changes to the database schema programmatically in Laravel.

We are going to use the given command to run database migrations.

php artisan migrate

Create Model File

In Laravel, a model class is used to interact with the table in the database, where each model illustrates a single row in the table.

Theoretically, Models are used to fetch data from the database, insert new records, update existing data, and remove data.

php artisan make:model UsaState

You have to look for the newly generated UsaState.php file inside the app/Models directory.


namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class UsaState extends Model
{
    use HasFactory;
    protected $table = "usa_states";
    protected $fillable = ['name', 'code'];
}

Build USA State Seeder

A Laravel seeder is a class used to seed a database with data for testing or initial setup purposes.

Here is the command that you have to invoke.

php artisan make:seeder UsaStateSeeder

We have defined the table properties in the seeder file; now, we have to register the seeder class in the database/seeds/DatabaseSeeder.php file.


namespace DatabaseSeeders;
use IlluminateDatabaseSeeder;
use AppModelsUsaState;
class UsaStateSeeder extends Seeder
{
    
    public function run()
    {
        UsaState::truncate();
  
        $states = [
              ["name" => "Alabama", "code" => "AL"],
              ["name" => "Alaska", "code" => "AK"],
              ["name" => "Arizona", "code" => "AZ"],
              ["name" => "Arkansas", "code" => "AR"],
              ["name" => "California", "code" => "CA"],
              ["name" => "Colorado", "code" => "CO"],
              ["name" => "Connecticut", "code" => "CT"],
              ["name" => "Delaware", "code" => "DE"],
              ["name" => "District of Columbia", "code" => "DC"],
              ["name" => "Florida", "code" => "FL"],
              ["name" => "Georgia", "code" => "GA"],
              ["name" => "Hawaii", "code" => "HI"],
              ["name" => "Idaho", "code" => "ID"],
              ["name" => "Illinois", "code" => "IL"],
              ["name" => "Indiana", "code" => "IN"],
              ["name" => "Iowa", "code" => "IA"],
              ["name" => "Kansas", "code" => "KS"],
              ["name" => "Kentucky", "code" => "KY"],
              ["name" => "Louisiana", "code" => "LA"],
              ["name" => "Maine", "code" => "ME"],
              ["name" => "Maryland", "code" => "MD"],
              ["name" => "Massachusetts", "code" => "MA"],
              ["name" => "Michigan", "code" => "MI"],
              ["name" => "Minnesota", "code" => "MN"],
              ["name" => "Mississippi", "code" => "MS"],
              ["name" => "Missouri", "code" => "MO"],
              ["name" => "Montana", "code" => "MT"],
              ["name" => "Nebraska", "code" => "NE"],
              ["name" => "Nevada", "code" => "NV"],
              ["name" => "New Hampshire", "code" => "NH"],
              ["name" => "New Jersey", "code" => "NJ"],
              ["name" => "New Mexico", "code" => "NM"],
              ["name" => "New York", "code" => "NY"],
              ["name" => "North Carolina", "code" => "NC"],
              ["name" => "North Dakota", "code" => "ND"],
              ["name" => "Ohio", "code" => "OH"],
              ["name" => "Oklahoma", "code" => "OK"],
              ["name" => "Oregon", "code" => "OR"],
              ["name" => "Pennsylvania", "code" => "PA"],
              ["name" => "Rhode Island", "code" => "RI"],
              ["name" => "South Carolina", "code" => "SC"],
              ["name" => "South Dakota", "code" => "SD"],
              ["name" => "Tennessee", "code" => "TN"],
              ["name" => "Texas", "code" => "TX"],
              ["name" => "Utah", "code" => "UT"],
              ["name" => "Vermont", "code" => "VT"],
              ["name" => "Virginia", "code" => "VA"],
              ["name" => "Washington", "code" => "WA"],
              ["name" => "West Virginia", "code" => "WV"],
              ["name" => "Wisconsin", "code" => "WI"],
              ["name" => "Wyoming", "code" => "WY"]
            ];
  
        foreach ($states as $key => $data) {
            UsaState::create($data);
        }
    }  
}

Populate Database with US Records

So far, we have connected every point that is run to populate USA state data into the database.

Ensure to evoke the given command and check the records in the database.

php artisan db:seed --class=UsaStateSeeder

How to Seed US States in Database using Laravel 9 Seeder

Conclusion

A database of US states typically consists of a table with columns that store information about each state, such as its name, abbreviation, capital, population, and area.

For the demo purpose, We created a new migration table with only the state name and code. However, you may add as many columns as you want.

This tutorial taught us how to insert US state records in the database within the foundation of the Laravel 9 framework.

Leave a Reply

Your email address will not be published. Required fields are marked *