Creating the back-end of a Laravel 9 blog using MySQL database

The goal of this tutorial is to teach, step-by-step, how to create a simple Laravel 9 blog application. The main focus here is in the architecture and back-end, although some front-end features will also be added in a future tutorial.

For this tutorial, I’m using the following versions (extracted from composer.json):

"require": {
"php": "^8.0.2",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/sanctum": "^3.0",
"laravel/tinker": "^2.7"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/breeze": "^1.13",
"laravel/pint": "^1.0",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},

Like in any MVC framework, the first step is to define which entities the system will need and how they relate each other. This is my idea for this system:

With this model in mind, it is clear that we will need 4 entities: User, Post, Comment and Tag. Each of these entities will became a Model in our application and consequently a table in a relational DBMS; but we will need another table for holding the m:n relationship between Post and Tag.

Before we start coding you must ensure that you have installed PHP 8.1 or greater on your computer; also you must have installed / enabled some PHP extensions — I recommend mysql, intl, mbstring, curl and xml, although I’m not sure if all of them will be needed for this Laravel app. You also need to have installed NodeJS (version 14 or greater), NPM, Composer (one of the most commons PHP dependency manager) and MySQL Server. If you don’t have it, please check on the internet how to install them 😉

Create project

First, open the terminal, change directory to you workspace directory (cd …), and type the following commands:

composer create-project laravel/laravel simple-blog --prefer-dist

Install starter kit

After downloading all dependencies, you should open your preferred editor on the new simple-blog directory — I recommend Visual Code with Intelephense extension.

Now, let’s go into the directory and install the Laravel Starter Kit Breeze:

cd simple-blog
composer require laravel/breeze --dev
php artisan breeze:install

Setting up the database

Next we need to prepare our database for storing the application data. In this step you need to access the DBMS Server (that must be running), create a new database and optionally a new user. You can do that through phpMyAdmin, Mysql Workbench or any other interface you prefer. Here I will show how to do to it directly from the terminal:

mysql -u root -pmysql> create database simple_blog;
mysql> create user 'laravel_user' identified by 'laravel_pw';
mysql> grant all privileges on simple_blog.* to 'laravel_user';

Now press ctrl+d(or command+con Mac) to exit the MySQL CLI and let’s go to set up these fresh new created database and user on our environment file. To do this, open the .env file and locate the line started by DB_DATABASE; this will hold the name of the database (simple_blog); similarly, DB_USERNAME and DB_PASSWORD will keep username and password that application will use to access the DBMS:

In order to check if everything is ok, type php artisan db; if it access the MySQL CLI then you should follow. If you experience some error, check if the DBMS server is running and you enabled / installed the PHP mysql extension (these are the more common mistakes in this step).

Migrating tables and testing

Now lets create database tables and run the application server in order to test it:

php artisan migrate
php artisan serve

Open your browser on localhost:8000 and you should see the welcome page for the application:

The Register and Log in links should have been fully working, so you can test it.

Creating other entities and migrations

If you open the database/migrations and/or app/Models directory you’ll see that Laravel came out with the User model and migration. Now we must create the other models with the migrations:

php artisan make:model Post -mfsr
php artisan make:model Comment -mfsr
php artisan make:model Tag -mfsr
php artisan make:migration create_post_tag_table

Note that I’m using the -mfsr options here in order to create the Model alongside with its migration (for create database table), factory and seeder (for generating fake data for the sake of tests) and a resource Controller. All this will be covered later in this tutorial.

Now let’s add some columns to our models:

Migrating new tables

With the columns filled, run the following command to run the migrations:

php artisan migrate

Remember that once you run a migration or push a new migration in a Continuous Integration workflow you should not change that migration anymore. If you need to change anything in the database modelling, create another migration to do that.

Filling the models classes

Now we can add the columns into the $fillable attribute of the related model classes (inside app/Models directory):

Adding relationships

Now it’s time to add some relationships. As we are using Eloquent ORM on Laravel, relationships are usually not exported to database, so this must be done in application level. Laravel and Eloquent provides us a powerful tool for creating relationships inside models:

Testing models and relationships

Laravel provides us a great CLI command based on the Psy Shell project, accessible through the command php artisan tinker . The shell is rooted on our project directory and has some shortcuts to our Model classes:

Using this you can play with all classes and relationships, creating new records and accessing them.

Implementing factories

Now, let’s improve our testing data by creating factories and seeders for our system, so we can start a fresh new database with fake generated data. This will greatly help us when developing our front-end.

First, we will implement our factories, that will be used to generate model instances with random fake generated data. Laravel bring us the UserFactory class (database/factories) already filled; if you want, you can change the hashed password to something more accessible:

Similarly, we will create now the other classes factories:

Checking seeders, models and relationships

With this, you can try the following commands on the tinker shell:

User::factory()->make() // creates an instance
User::factory()->make()->save() // creates an instance and store it
User::factory()->create() // same above, but shorter
User::factory(5)->create() // creates and saves 5 users
Post::factory(5)->create
Comment::factory(5)->create
Tag::factory(5)->create
Post::find(1)->tags()->attach(Tag::all()->random())
Post::find(2)->tags()->attach(Tag::all()->random(3))
Post::find(2)->tags
Tag::find(1)->posts
// ...

Seeders

Now that we are able to random generate records for our database, we can create the seeders for auto seed database with fake data, so we can start our application with some data in order to test it.

To achieve this, we’ll implement Seeders classes inside database/seeders directory:

We will also create a PostTagSeeder so we can some random relationships between posts and tags. Although you can create it directly into the directory, it is best to create through the artisan:

php artisan make:seeder PostTagSeeder

You must have in mind that by default only the DatabaseSeeder class is called when running the artisan command, so we need to make it call the other seeders:

After this, you can run the following command on your terminal:

php artisan migrate:fresh --seed

This will recreate your database and seed it according with the DatabaseSeeder class (you can check it with tinker).

Conclusion

This concludes this tutorial, that is fully focused on the back-end of a Laravel application. The next step is to create the front-end, using Blade templates, Vue, React or other supported front-end framework, but this is for another tutorial.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ranieri Valenca

Ranieri Valenca

Full Stack Web Developer and Teacher