Powerful Applications with Laravel — Database and Migrations

Gabriel Meireles
dev.meireles
Published in
4 min readMar 11, 2023
Photo by C M on Unsplash

After knowing that controllers are responsible for route commands for our application, that’s time to explain a bit about model which is also a pretty important layer of MCV. Briefly models are responsible for handle data and business logic on an application. With a model we have control about what kind of data the app have control, send and receive data operations to a controller.

Model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). — Applications Programming in Smalltalk-80 (TM): How to use Model-View-Controller (MVC) — Steve Burbeck

I dare to say that nowadays almost all applications in somehow depends on a database connection whether it a real DBMS, a cache system or even a text file. There’s a widely quantity of applications which uses database, as examples applications that we’re are used to interact in our daily life that stores credential access, emails, images, movies, allow us to watch a video, read an article, ask for a cab or whatever is it, they need to have some way to store data.

Connecting to database

Take into account Laravel is fully flexible in terms of database providing support for five databases, MariaDB, MySQL, PostgreSQL, SQLite and SQL Server, besides, there are other possibilities as DynamoDB with Laravel DynamoDB, MongoDB with Laravel MongoDB, Oracle with Laravel-OCI8 and so on.

For this series we`re going to use PostgreSQL database, so if you’re using the initial Docker repository featured in the first part of this series you can easily get the environment variables for database on docker-compose.yml file under the postgres section, but feel free to user a database connection of your choice. So if you don`t have a .env file yet, please copy the .env.example and update according to the following section:

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=laraveldb
DB_USERNAME=postgres
DB_PASSWORD=password

Migrations

Migrations look like a git version control allowing the developer to properly handle database schemas from their current state to a new desired state that includes actions like adding tables, columns, relationships and also remove them.
As properly stated in Laravel documentation: “migrations are like version control for your database, allowing your team to define and share the application’s database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you’ve faced the problem that database migrations solve.

With Artisan we’ve different alternatives to generate migrations, so you can generate a simple migration file using:
(Make sure to access your docker container, all following commands will be executed inside there)

php artisan make:migration create_products_table

On app/database/migrations folder it’ll creates a PHP file containing the generated migration script:

<?php

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

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};

A quickly explanation:

  • With Schema::create Laravel generates the table, the first parameter is the table name and the second a callback containing the table properties.
  • Using the Blueprint class through the $table variable you can set your table properties, it’s basically setting the table id using the bigIncrements type that’ll setup the necessary properties for an id type

I recommend you to take a look on Available Column Types on Laravel documentation, after that try to add some columns and finally execute your migration with:

php artisan migrate

After that if everything went as expected it must generate you products table, so you can see them using some database GUI tool of your choice or use the pgAdmin that’s included on our docker setup accessing http://localhost:5050/ with admin@example.com as user and password as password.

Now it’s time to rollback the product table, we’ll do some changes:

php artisan migrate:rollback

As said before, there’re some another ways to generate migrations, so let’s try them.

With the make:model we can use some parameters like -c to say we want to have a controller for this created model, -m for migration and -r for the created controller resources, what means, it’ll create the CRUD scaffolding for this current entity. I recommend you to take a look on Generating Model Classes section on Laravel documentation:

For this step make sure to remove the previous create_products_table migration file, then let’s create a product model, to se how it goes:

php artisan make:model Product --migration

With that now we’ve a file for Product as model and a create_products_table as migration.

On products migration file, let`s add some columns as:

<?php

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

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->longText('description');
$table->double('price');
$table->boolean('active')->default(true);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};

Then finally it’s time do definitively migrate, so on you terminal do the following command:

php artisan migrate

On pgAdmin you can see you recently created table:

So far that’s all folks, see you next step to start the Controller + Model interactions. All current updates are place on GitHub repository, feel free to explore them.

--

--