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.zip
Copy 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 update
Copy Code
Then we install the unzip package:
$ sudo apt install unzip
Copy Code
Following that, we unzip the contents of the application:
$ unzip travellist.zip
Copy Code
Then we rename the unpacked directory to
travellist-demo
Copy Code
for easier access:
$ mv travellist-laravel-demo-tutorial-2.0.1 travellist-demo
Copy 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-demo
Copy Code
directory:
$ cd travellist-demo
Copy 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 .env
Copy Code
We open this file using nano or text editor of choice:
$ nano .env
Copy 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
travellist
Copy 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
travellist
Copy 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 -d
Copy 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 … done
Copy 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.
$ composer install
Copy Code
To execute the composer install in the app container, we run:
$ docker-compose exec app composer install
Copy 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:wipe
Copy 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:migration
Copy Code
command as follows:
$ docker-compose exec app php artisan make:migration create_places_table
Copy 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:migration
Copy Code
command.
We will see output similar to this:
Created Migration: 2020_02_03_143622_create_places_table
Copy Code
This will generate a new file in the application’s database/migrations directory. Laravel uses the
timestamp
Copy 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.php
Copy 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: up
Copy Code
and down
Copy Code
.
up
Copy Codedown
Copy CodeWe will modify the
up
Copy Code
method so that the places table reflects the structure we are already using in the current application’s version:
: primary key field.id
Copy Code
: name of the place.name
Copy Code
: whether or not this place was already visited.visited
Copy Code
The Laravel schema builder exposes methods for creating, updating, and deleting tables in a database. The
Blueprint
Copy 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
id
Copy Code
. The timestamps
Copy Code
method creates two datetime
Copy 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
name
Copy Code
and a visited
Copy Code
field.
Our
name
Copy Code
field will be of type string
Copy Code
, and our visited
Copy Code
field will be set with the boolean
Copy Code
type. We will also set a default value of 0
Copy Code
for the visited
Copy Code
field, so that if no value is passed, it means the place was not visited yet.
This is how the
up
Copy 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
artisan
Copy Code
command to generate a new seeder class for our places
Copy Code
table called PlacesTableSeeder
Copy Code
:
$ docker-compose exec app PHP artisan make:seeder PlacesTableSeeder
Copy Code
The command will create a new file,
PlacesTableSeeder.php
Copy Code
inside the database/seeds
Copy Code
directory.
We open that file using text editor:
$ nano database/seeds/PlacesTableSeeder.php
Copy Code
This is what the auto-generated
PlacesTableSeeder.php
Copy 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
run
Copy Code
. This method will be called when we execute the db:seed
Copy 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
foreach
Copy Code
loop to iterate through all values, inserting each one in the database using the query builder.
We will call this variable $places
Copy Code
:
$places
Copy 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
use
Copy Code
statement at the top of our PlacesTableSeeder
Copy Code
class to facilitate referencing the DB
Copy Code
facade throughout the code:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PlacesTableSeeder extends Seeder
…
Copy Code
We can now iterate through the
$places
Copy Code
array values using a foreach
Copy Code
loop, and insert each one in our places
Copy 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
foreach
Copy Code
loop iterates through each value of the $places
Copy Code
static array. At each iteration, we use the DB
Copy Code
facade to insert a new row at the places
Copy Code
table.
We set the
name
Copy Code
field to the name of the place we just obtained from the $places
Copy Code
array, and we set the visited
Copy Code
field to a random value of either 0
Copy Code
or 1
Copy Code
.
This is what the full
PlacesTableSeeder
Copy 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
DatabaseSeeder
Copy Code
class to include a call to the seeder we have just created.
We open the
database/seeds/DatabaseSeeder.php
Copy Code
file using nano
Copy Code
or any editor:
$ nano database/seeds/DatabaseSeeder.php
Copy Code
The
DatabaseSeeder
Copy Code
class looks like any other seeder: it extends from the Seeder
Copy Code
class and has a run
Copy Code
method. We will update this method to include a call to PlacesTableSeeder
Copy Code
.
We update the current run method inside our
DatabaseSeeder
Copy 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
place
Copy 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:generate
Copy Code
command:
$ docker-compose exec app php artisan key:generate
Copy 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:8000
Copy Code
Then we will see a page like this:
That means the application is able to connect to the database, but it could not find a table called
places
Copy Code
.
We create the
places
Copy Code
table using the following migrate artisan
Copy Code
command:
$ docker-compose exec app php artisan migrate
Copy 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_table
Copy 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:see
Copy Code
d command to seed
Copy Code
the database with our sample places:
$ docker-compose exec app php artisan db:seed
Copy Code
This will run our seeder and insert the sample values within our
PlacesTableSeeder
Copy 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:wipe
Copy 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 –seed
Copy 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:rollback
Copy 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:wipe
Copy 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.
0 Comments