Share this:

In Laravel 9, database seeding is a useful feature that allows developers to populate a database with test data. This can be particularly helpful when testing an application’s functionality or when building a new application that requires sample data. In this guide, we will be discussing how to seed US states into a database using Laravel 9 seeder.

This is an example of using Laravel 9 to seed a database with US state information. To achieve this, you would follow these steps:

  1. Download the Laravel framework
  2. Connect to your database
  3. Create a migration file
  4. Create a model file
  5. Build the seeder for US states
  6. Populate your database with the US state information

Download the 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:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('usa_states', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('code');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    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.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
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.

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\UsaState;
class UsaStateSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    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.

Share this:

Categorized in: