Laravel-2 Database Setup

Kaidong Wu
Apr 11 · 3 min read

1. Difference between database.php and .env

.env is short for environment and thus that is your environment configurations. The database.php configuration contains non-critical information. You obviously won’t have your database’s username’s password in your source control or available in the code. In order to keep everything safe or to keep information saved that is environment-defined… you keep them in .env file

Laravel will prioritize .env variables.

Because the .env configuration would vary among different database setup. Thus git would ignore the .env file by default, remember to add .env when you pull a whole a new laravel project at the first time.

2. Setup

2.1 With ready-to-use database schema

If we already have the database schema and tables ready, then we don’t have to do migrate, what we need to do is to create the corresponding model with the following commands:

This command would create a Eloquent model under app folder. Then inside each newly created model, just specify the table name and primary key in the class:

2.2 From Laravel model to actual database tables:

If there is no any table ready for laravel, then we should create the corresponding models and migrations in Laravel:

The -m parameter will also create the corresponding migration file of the model

By convention, the “snake case”, plural name of the model class will be used as the table name

Then add any table column (fields) you want in the up method of migration files.

After finish the creation of models and migrations, then run the migration commands:

Sometime problem can be encounted that prompt that can’t find database driver at the database.php file. Please uncomment the line extension=pdo_mysql in the php.ini configuration file (For those developer that are using xamp/mamp/wamp, you can enable this extension at their php extension menu options)

Sometime problem will be encountered when some of the tables fails to migrate due to the foreign key constraint, this means that the foreign keys migrations files is declared before the declaration of the corresponding primary key table. In order to change the migration order of the migration files, you need to change the migration creation time in the file name based on the order. Then re-execute the command php artisan migrate:fresh

This command would apply all the migration changes in laravel to the databases. Here are some other useful migration commands:

Sometimes there is annoying if we are adding a new table, but when run the database migration command, it would flush away all the exiting data and remigrate the whole database. If we want to add new table into database without affecting the exiting tables and data, here is a work around:

Create new folder in “database/migrations/” and use the “path” property on migrate , Once the table is migrated, you can move the migration file back to the usual folder.