×


Working with Database Configuration in Laravel

Need support with database configuration in Laravel?

This guide will help you.


Laravel makes connecting with databases and running queries extremely simple. The database configuration file is "app/config/database.php" . 

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform Website and Database migration tasks.

In this context, we shall look into Database Configuration in Laravel and its execution.


More about 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 case, we shall create migrations and seeders to populate a Laravel demo application's database with sample data.


In order to set database configuration in Laravel, ensure the following:

i. 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.

ii. Docker installed on the server.

iii. Docker Compose installed on the server.


How to perform Database Configuration in Laravel ?

Here, we will use a containerized development environment by Docker Compose to run the application. However, we can also opt to run the application on a LEMP (Nginx) server.


The steps to perform Database Configuration in Laravel is outlined below;


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.zip

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 update

Then we install the unzip package:

$ sudo apt install unzip

Following that, we unzip the contents of the application:

$ unzip travellist.zip

Then we rename the unpacked directory to travellist-demo for easier access:

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

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


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-demo directory:

$ cd travellist-demo

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 .env

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

$ nano .env

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

The current .env file from the travellist 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.


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 travellist 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 -d

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 … done

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 install

To execute the composer install in the app container, we run:

$ docker-compose exec app composer install

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%)

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:wipe

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.


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


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:migration command as follows:

$ docker-compose exec app php artisan make:migration create_places_table

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:migration command.


We will see output similar to this:

Created Migration: 2020_02_03_143622_create_places_table

This will generate a new file in the application’s database/migrations directory. Laravel uses the timestamp 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.php

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’);
}
}

This class has two methods: up and down.


We will modify the up method so that the places table reflects the structure we are already using in the current application’s version:

id: primary key field.

name: name of the place.

visited: whether or not this place was already visited.


The Laravel schema builder exposes methods for creating, updating, and deleting tables in a database. The Blueprint 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 id. The timestamps method creates two datetime 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 name and a visited field.

Our name field will be of type string, and our visited field will be set with the boolean type. We will also set a default value of 0 for the visited field, so that if no value is passed, it means the place was not visited yet.


This is how the up 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();
});
}

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.]


5. How to 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 artisan command to generate a new seeder class for our places table called PlacesTableSeeder:

$ docker-compose exec app PHP artisan make:seeder PlacesTableSeeder

The command will create a new file, PlacesTableSeeder.php inside the database/seeds directory.


We open that file using text editor:

$ nano database/seeds/PlacesTableSeeder.php

This is what the auto-generated PlacesTableSeeder.php file will look like:

<?php
use Illuminate\Database\Seeder;
class PlacesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
}
}

Our new seeder class contains an empty method named run. This method will be called when we execute the db:seed 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 foreach loop to iterate through all values, inserting each one in the database using the query builder.

We will call this variable $places:

<?php
use Illuminate\Database\Seeder;
class PlacesTableSeeder extends Seeder
{
static $places = [
‘Berlin’,
‘Budapest’,
‘Cincinnati’,
‘Denver’,
‘Helsinki’,
‘Lisbon’,
‘Moscow’,
‘Nairobi’,
‘Oslo’,
‘Rio’,
‘Tokyo’
];


Next, we need to include a use statement at the top of our PlacesTableSeeder class to facilitate referencing the DB facade throughout the code:

<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PlacesTableSeeder extends Seeder


We can now iterate through the $places array values using a foreach loop, and insert each one in our places table using the query builder:


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


The foreach loop iterates through each value of the $places static array. At each iteration, we use the DB facade to insert a new row at the places table.


We set the name field to the name of the place we just obtained from the $places array, and we set the visited field to a random value of either 0 or 1.


This is what the full PlacesTableSeeder 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
]);
}
}
}

Then, we save and close the file.


Seeder classes do not load automatically in the application. We need to edit the main DatabaseSeeder class to include a call to the seeder we have just created.


We open the database/seeds/DatabaseSeeder.php file using nano or any editor:

$ nano database/seeds/DatabaseSeeder.php

The DatabaseSeeder class looks like any other seeder: it extends from the Seeder class and has a run method. We will update this method to include a call to PlacesTableSeeder.


We update the current run method inside our DatabaseSeeder class by deleting the commented-out line and replacing it with the following highlighted code:


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

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);
}
}

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 place table. In the next step, we will see how our Support Engineers execute them.


[Confused with Seeders when Migrating Databases? We are available 24*7.]


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:generate command:

$ docker-compose exec app php artisan key:generate

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:8000

Then we will see an error page like this:

Base table not found...

This simply means the application is able to connect to the database, but it could not find a table called places.


We create the places table using the following migrate artisan command:

$ docker-compose exec app php artisan migrate

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)

We can see the execution of a few other migrations along with the create_places_table 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:seed command to seed the database with our sample places:

$ docker-compose exec app php artisan db:seed

This will run our seeder and insert the sample values within our PlacesTableSeeder class.


We can see an output similar to this:

Seeding: PlacesTableSeeder
Seeded: PlacesTableSeeder (0.06 seconds)
Database seeding completed successfully.

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:wipe

Output

Dropped all tables successfully.

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

$ docker-compose exec app php artisan migrate –seed

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.

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

$ docker-compose exec app php artisan migrate:rollback

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)

The rollback command is especially useful when we make changes to application models and a db:wipe command cannot be used.


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


[Stuck with the Database Migration execution? We'd be happy to assist you today. ]


Conclusion

This article will guide you on steps to set up #development and testing databases for Laravel by using database migrations and #seeders. Database migration means moving your data from one platform to another. To run #laravel migrations, first you have to configure your #database connection, and then you use Artisan, Laravel's #command line interface, to install the migrations table and run, revert, create. This command causes #Artisan to create a special table in your database to keep track of what #migrations have already been executed.