Bobcares

Database Configuration in Laravel – How to use Migrations and Seeders

by | Jan 6, 2021

Need help with database configuration in Laravel? We can help you.

As part of our Server Management Services, we assist our customers with several migration requests.

Today, let us focus on Database Configuration in Laravel and its execution.

 

Migrations and Seeders

Migrations and seeders are powerful database utilities by the Laravel PHP framework. These utilities help to minimize database inconsistency problems that can arise with multiple developers working on the same application.

In this article, we create migrations and seeders to populate a Laravel demo application’s database with sample data.

In order to set database configuration in Laravel, our Support Engineers suggest having:

  • Access to an Ubuntu 18.04 local machine or development server as a non-root user with Sudo privileges. If we use a remote server, we have an active firewall installed.
  • Docker installed on the server.
  • Docker Compose installed on the server.

 

Database Configuration in Laravel

Our Support Techs use a containerized development environment by Docker Compose to run the application. However, we can also opt to run the application on a LEMP server.

Let us now focus on a few steps guiding to Database Configuration in Laravel.

 

Step 1 – Obtain the Demo Application

To begin we will fetch the demo Laravel application from its GitHub repository.

In this example, we will download the application to our home folder. However, we can use any directory of choice:

$ cd ~
$ curl -L https://github.com/do-community/travellist-laravel-demo/archive/tutorial-2.0.1.zip -o travellist.zipCopy Code

Since we have the application code as a .zip file, we will need the unzip command to unpack it.

If we have not done so recently, we need to update the machine’s local package index:

$ sudo apt updateCopy Code

Then we install the unzip package:

$ sudo apt install unzipCopy Code

Following that, we unzip the contents of the application:

$ unzip travellist.zipCopy Code

Then we rename the unpacked directory to

travellist-demoCopy Code
for easier access:

$ mv travellist-laravel-demo-tutorial-2.0.1 travellist-demoCopy Code

In the next step, we will create a .env configuration file to set up the application.

 

Step 2 – Set Up the Application’s .env File

In Laravel, we use a .env file to set up environment-dependent configurations. These are credentials and information that might vary between deployments.

The environment configuration file contains sensitive information, including database credentials and security keys. Hence, we should never share this file publicly.

The values in the .env file will take precedence over the values set in regular configuration files in the config directory.

Each installation on a new environment requires a tailored environment file to define things such as database connection settings, debug options, and the application URL, among other items.

Navigate to the

travellist-demoCopy Code
directory:

$ cd travellist-demoCopy Code

We will now create a new .env file to customize the configuration options for the development environment we set up.

Laravel comes with an example.env file that we can copy to create our own:

$ cp .env.example .envCopy Code

We open this file using nano or text editor of choice:

$ nano .envCopy Code

This is how our .env file will look:

APP_NAME=Travellist
APP_ENV=dev
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=travellist
DB_USERNAME=travellist_user
DB_PASSWORD=password
…Copy Code

The current .env file from the

travellistCopy Code
demo application contains settings to use the containerized environment.

We do not need to change any of these values, but we are free to modify the DB_DATABASE, DB_USERNAME, and DB_PASSWORD.

We make sure the DB_HOST variable does not change since it references the name of our database service within the Docker Compose environment.

If we make any changes to the file, we make sure to save and close it by pressing CTRL + X, Y, then ENTER.

If we opt to run the application on a LEMP server, we need to change the highlight values to reflect our own database settings, including the DB_HOST variable.

 

Step 3 – Install Application Dependencies with Composer

We will now use Composer, PHP’s dependency management tool, to install the application’s dependencies. Similarly, we make sure we are able to execute artisan commands.

We bring up our Docker Compose environment with the following command.

It will build the

travellistCopy Code
image for the app service and pull in the additional Docker images required by the Nginx and DB services, in order to create the application environment:

$ docker-compose up -dCopy Code
Output:
Creating network “travellist-demo_travellist” with driver “bridge”
Building app
Step 1/11 : FROM php:7.4-fpm
—> fa37bd6db22a
Step 2/11 : ARG user
—> Running in 9259bb2ac034
…
Creating travellist-app … done
Creating travellist-nginx … done
Creating travellist-db … doneCopy Code

This operation might take a few minutes to complete. Once done, we can run Composer to install the application’s dependencies.

To execute composer and other commands in the app service container, we will use docker-compose exec.

The exec command allows us to execute any command of our choice on containers managed by Docker Compose. It uses the following syntax: docker-compose exec service_name command.

In case we opt to use a LEMP server to run the demo application, we should ignore the docker-compose exec app portion of the commands in this article. For example, we would just run:
$ composer installCopy Code
To execute the composer install in the app container, we run:
$ docker-compose exec app composer installCopy Code
Output:
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 85 installs, 0 updates, 0 removals
– Installing doctrine/inflector (1.3.1): Downloading (100%)
– Installing doctrine/lexer (1.2.0): Downloading (100%)
– Installing dragonmantank/cron-expression (v2.3.0): Downloading (100%)
…Copy Code

When the Composer installs the application’s dependencies, we will be able to execute artisan commands.

To test that the application is able to connect to the database, run the following command which will clean up any pre-existing tables:

$ docker-compose exec app php artisan db:wipeCopy Code

This command will drop any pre-existing tables on the configured database. If it ran successfully and the application is able to connect to the database, we will see output like this:

Dropped all tables successfully.Copy Code

Now that we have installed the application dependencies with Composer, we can use the artisan tool to create migrations and seeders.

 

Step 4 – Create Database Migrations

The artisan command-line tool that ships with Laravel contain a series of helper commands to manage the application and bootstrap new classes.

To generate a new migration class, we can use the

make:migrationCopy Code
command as follows:

$ docker-compose exec app php artisan make:migration create_places_tableCopy Code

Laravel infers the operation to execute, the name of the table, and whether this migration will create a new table or not, based on the descriptive name provided to the

make:migrationCopy Code
command.

We will see output similar to this:

Created Migration: 2020_02_03_143622_create_places_tableCopy Code

This will generate a new file in the application’s database/migrations directory. Laravel uses the

timestampCopy Code
in the auto-generate file to determine in which order migrations should be executed.

We use a text editor to open the migration file. Remember to replace the highlight value with our own migration file name:

$ nano database/migrations/2020_02_03_143622_create_places_table.phpCopy Code

The migration file contains a class, CreatePlacesTable:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePlacesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘places’, function (Blueprint $table) {
$table->bigIncrements(‘id’);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(‘places’);
}
}Copy Code
This class has two methods:
upCopy Code
and
downCopy Code
.

We will modify the

upCopy Code
method so that the places table reflects the structure we are already using in the current application’s version:

The Laravel schema builder exposes methods for creating, updating, and deleting tables in a database. The

BlueprintCopy Code
class defines the table’s structure. It also provides several methods to abstract the definition of each table field.

The auto-generated code sets up a primary id field called

idCopy Code
. The
timestampsCopy Code
method creates two
datetimeCopy Code
fields that automatically update by the underlying database classes when we insert or update the data within that table.

In addition to these, we will need to include a

nameCopy Code
and a
visitedCopy Code
field.

Our

nameCopy Code
field will be of type
stringCopy Code
, and our
visitedCopy Code
field will be set with the
booleanCopy Code
type. We will also set a default value of
0Copy Code
for the
visitedCopy Code
field, so that if no value is passed, it means the place was not visited yet.

This is how the

upCopy Code
method will look like:

…
public function up()
{
Schema::create(‘places’, function (Blueprint $table) {
$table->bigIncrements(‘id’);
$table->string(‘name’, 100);
$table->boolean(‘visited’)->default(0);
$table->timestamps();
});
}
…Copy Code

After we add the two highlight lines on our own migration script, we save and close the file.

The migration is now ready to execute via artisan migrate. However, that will only create an empty table; we also need to be able to insert sample data for development and testing.

[Need help with Database Migrations? We are here for you]

 

Step 5 – Create Database Seeders

A seeder is a special class to generate and insert sample data (seeds) in a database. This is an important feature in development environments since it allows us to recreate the application with a fresh database.

We will now use the

artisanCopy Code
command to generate a new seeder class for our
placesCopy Code
table called
PlacesTableSeederCopy Code
:

$ docker-compose exec app PHP artisan make:seeder PlacesTableSeederCopy Code

The command will create a new file,

PlacesTableSeeder.phpCopy Code
inside the
database/seedsCopy Code
directory.

We open that file using text editor:

$ nano database/seeds/PlacesTableSeeder.phpCopy Code

This is what the auto-generated

PlacesTableSeeder.phpCopy Code
file will look like:

<?php

use Illuminate\Database\Seeder;

class PlacesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
}
}Copy Code

Our new seeder class contains an empty method named

runCopy Code
. This method will be called when we execute the
db:seedCopy Code
Artisan command.

We need to edit the run method in order to include instructions to insert sample data in the database. We will use the Laravel query builder to streamline this process.

To get started, we will create a static class variable to hold all the sample places we want to insert into the database as an array.

This will allow us to use a

foreachCopy Code
loop to iterate through all values, inserting each one in the database using the query builder.

We will call this variable
$placesCopy Code
:
<?php

use Illuminate\Database\Seeder;

class PlacesTableSeeder extends Seeder
{
static $places = [
‘Berlin’,
‘Budapest’,
‘Cincinnati’,
‘Denver’,
‘Helsinki’,
‘Lisbon’,
‘Moscow’,
‘Nairobi’,
‘Oslo’,
‘Rio’,
‘Tokyo’
];
…Copy Code

Next, we need to include a

useCopy Code
statement at the top of our
PlacesTableSeederCopy Code
class to facilitate referencing the
DBCopy Code
facade throughout the code:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PlacesTableSeeder extends SeederCopy Code

We can now iterate through the

$placesCopy Code
array values using a
foreachCopy Code
loop, and insert each one in our
placesCopy Code
table using the query builder:

public function run()
{
foreach (self::$places as $place) {
DB::table(‘places’)->insert([
‘name’ => $place,
‘visited’ => rand(0,1) == 1
]);
}
}Copy Code

The

foreachCopy Code
loop iterates through each value of the
$placesCopy Code
static array. At each iteration, we use the
DBCopy Code
facade to insert a new row at the
placesCopy Code
table.

We set the

nameCopy Code
field to the name of the place we just obtained from the
$placesCopy Code
array, and we set the
visitedCopy Code
field to a random value of either
0Copy Code
or
1Copy Code
.

This is what the full

PlacesTableSeederCopy Code
class will look like after all the updates:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class PlacesTableSeeder extends Seeder
{
static $places = [
‘Berlin’,
‘Budapest’,
‘Cincinnati’,
‘Denver’,
‘Helsinki’,
‘Lisbon’,
‘Moscow’,
‘Nairobi’,
‘Oslo’,
‘Rio’,
‘Tokyo’
];

/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
foreach (self::$places as $place) {
DB::table(‘places’)->insert([
‘name’ => $place,
‘visited’ => rand(0,1) == 1
]);
}
}
}Copy Code

Then, we save and close the file.

Seeder classes do not load automatically in the application. We need to edit the main

DatabaseSeederCopy Code
class to include a call to the seeder we have just created.

We open the

database/seeds/DatabaseSeeder.phpCopy Code
file using
nanoCopy Code
or any editor:

$ nano database/seeds/DatabaseSeeder.phpCopy Code

The

DatabaseSeederCopy Code
class looks like any other seeder: it extends from the
SeederCopy Code
class and has a
runCopy Code
method. We will update this method to include a call to
PlacesTableSeederCopy Code
.

We update the current run method inside our

DatabaseSeederCopy Code
class by deleting the commented-out line and replacing it with the following highlighted code:

public function run()
{
$this->call(PlacesTableSeeder::class);
}
…Copy Code

This is how the full DatabaseSeeder class will look like after the update:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
/**
* Seed the application’s database.
*
* @return void
*/
public function run()
{
$this->call(PlacesTableSeeder::class);
}
}Copy Code

We save and close the file when we are done updating its content.

We have now finished setting up both migration and a seeder for our

placeCopy Code
table. In the next step, we will see how our Support Engineers execute them.

[Confused with Seeders? We are available 24*7]

 

Step 6 – Run Database Migrations and Seeders

Before proceeding, we need to make sure our application is up and running. We will set up the application encryption key and then access the application from a browser to test the webserver.

To generate the encryption key by Laravel, we can use the artisan

key:generateCopy Code
command:

$ docker-compose exec app php artisan key:generateCopy Code

Once the key generates, we will be able to access the application by pointing our browser to our server hostname or IP address on port 8000:

http://server_host_or_ip:8000Copy Code

Then we will see a page like this:

Database Configuration in Laravel

That means the application is able to connect to the database, but it could not find a table called

placesCopy Code
.

We create the

placesCopy Code
table using the following migrate
artisanCopy Code
command:

$ docker-compose exec app php artisan migrateCopy Code

Our output will be similar to this:

Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.06 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.06 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.03 seconds)
Migrating: 2020_02_10_144134_create_places_table
Migrated: 2020_02_10_144134_create_places_table (0.03 seconds)Copy Code

We can see the execution of a few other migrations along with the

create_places_tableCopy Code
migration. These migrations are auto-generated when we install Laravel.

Although we will not be using these additional tables now, they will be of use in the future.

At this point, our table is still empty. We need to run the

 db:seeCopy Code
d command to
seedCopy Code
the database with our sample places:

$ docker-compose exec app php artisan db:seedCopy Code

This will run our seeder and insert the sample values within our

PlacesTableSeederCopy Code
class.

We can see an output similar to this:
Seeding: PlacesTableSeeder
Seeded: PlacesTableSeeder (0.06 seconds)
Database seeding completed successfully.Copy Code

Now, reload the application page on the browser.

Whenever we need to start from scratch, we can drop all our database tables with:

$ docker-compose exec app php artisan db:wipeCopy Code
Output
Dropped all tables successfully.Copy Code

To run the app migrations and seed the tables in a single command, we use:

$ docker-compose exec app php artisan migrate –seedCopy Code
Output:
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.06 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.07 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.03 seconds)
Migrating: 2020_02_10_144134_create_places_table
Migrated: 2020_02_10_144134_create_places_table (0.03 seconds)
Seeding: PlacesTableSeeder
Seeded: PlacesTableSeeder (0.06 seconds)
Database seeding completed successfully.Copy Code

If we want to roll back a migration, we run:

$ docker-compose exec app php artisan migrate:rollbackCopy Code

This will trigger the down method for each migration class inside the migrations folder.

Typically, it will remove all the tables that we create through migration classes, leaving alone any other tables that are manually created.

Our output will be like this:

Rolling back: 2020_02_10_144134_create_places_table
Rolled back: 2020_02_10_144134_create_places_table (0.02 seconds)
Rolling back: 2019_08_19_000000_create_failed_jobs_table
Rolled back: 2019_08_19_000000_create_failed_jobs_table (0.02 seconds)
Rolling back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_100000_create_password_resets_table (0.02 seconds)
Rolling back: 2014_10_12_000000_create_users_table
Rolled back: 2014_10_12_000000_create_users_table (0.02 seconds)Copy Code

The rollback command is especially useful when we make changes to application models and a

db:wipeCopy Code
command cannot be used.

For instance, if multiple systems depend on the same database.

[Stuck with the execution? We’d be happy to assist]

 

Conclusion

To conclude, Database Configuration in Laravel is possible with the use of database migrations and seeders. Today, we saw how our Support Engineers use these utilities to facilitate setting up development and testing databases for Laravel.

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

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

Speed issues driving customers away?
We’ve got your back!