Database Laravel PHP

Database migrations, PHP with Laravel

Database migrations are an awesome concept in software engineering that allow you to keep track of the state of your database. When I say state I mean history, you can go back in time and update and delete fields. It is also known as a schema migration.

I work with PHP using the Laravel framework. Laravel have an awesome command line tool called artisan, which you can use you create new databases, update existing fields, rename existing columns, new columns and delete fields.

Migrations allow you to make incremental changes to you database, you can go back in history and create the future by adding new fields to your database, it really is quite amazing.

Lets build a music app together. What do all music apps need? songs, great, so we need a table to store all of our songs, great.

What will our table look like? what fields do we need? Lets think about the data that we want to store for a minute. All songs have a title, an artist(s), the date it was made and maybe a remix artist.

There we have it we have just planned out out schema for our table.

  • id
  • title
  • artist
  • remixed_by
  • released

First create Laravel project

[sourcecode language=”bash” wraplines=”true” highlight=””]
// create project
laravel new muziks

// rename evn file
mv .env.example .env

// generat key
php artisan key:generate

// ok lets go…

// login to mysql (local but sure use docker if you like)
mysql -uroot -proot

// create database
| Database |
| muziks |

// run create
php artisan make:migration create_songs_table

You should have a time stamped file with the name of the migration
[sourcecode language=”bash” wraplines=”true” highlight=””]

Next open the migration file and lets fill in our schema, the fields of the table.

In out migration file we have up() and down() method. The up method will flesh out our planned schema. So when you do a php artisan migrate Laravel will go ahead and create the given table with the given fields. The down method will delete the table.

[sourcecode language=”php” wraplines=”true” highlight=””]

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

class CreateSongsTable extends Migration
* Run the migrations.
* @return void
public function up()
Schema::create(‘songs’, function (Blueprint $table) {
// Here we adding our tables’ fields

* Reverse the migrations.
* @return void
public function down()
// this will delete the table when


Next create the migrations.
[sourcecode language=”bash” wraplines=”true” highlight=””]
// run migrations
php artisan migrate

You should have a table like this:

If you want to rollback the migration, you can do this:
[sourcecode language=”bash” wraplines=”true” highlight=””]
// rollback migration
php artisan migrate:rollback

Leave a Reply