Get up to 80 % extra points for free! More info:

Lesson 6 - Simple CMS in Laravel - Migration

In the last lesson, Simple CMS in Laravel - Project structure, we described the structure of the Laravel application and created a new project.

In today's lesson, we will explain what migrations are and create our own. We continue in Laravel tutorial how to create simple CMS.

Database

We configured our database in the last lesson. However, we don't have to worry about the connection itself - the background framework solves it for us. To work with the database, we will use Eloquent ORM, where each database table has its own model (class) and through this model we work with the table. But how is the database structure managed in the Laravel framework?

Generating a database structure

Imagine a situation where we are working with someone on our project and then we need to change a column in a database table. How to achieve this elegantly? One solution is to share the MySQL code for this change with other developers of the application. However, this is very inefficient and unreliable. When uploading changes to the production server, some parts of the MySQL code may be forgotten and this would cause the application to malfunction. Such a situation must not occur with a real application, the customer would probably not be very satisfied :) For this and other reasons migrations have arisen.

Migrations are something like a database version. We modify the database structure through them using PHP code via a builder or by running MySQL commands. The advantage of migrations is that they are performed only once. In addition, we can go back in them, which is useful if we make a mistake in the development.

The migration can be found in the database/migrations/ folder, and if we open this folder now, we will find that it already contains 2 files. One file will generate a table of users and the second one a table for unsuccessful tasks running in the background (so-called jobs). We will explain the migration on the file 2014_10_12_000000_create_users_table.php, the content of which is as follows:

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Each migration consists of two methods: up() and down():

  • Use the up() method to change a database table (for example, to add a new column or a key).
  • The down() method is the exact opposite of the up() method. It will be called if we want to undo the changes.

We use the Schema builder to manage the database structure via migration. Then we pass an instance of the Blueprint class representing the table as a parameter.

Why does Laravel already basically contain these 2 migrations? As I wrote in the introductory lesson, Laravel is optimized for real web applications and therefore also contains the most frequently used tables. However, the more important reason (applies mainly to the user migrations) is that we can have the entire part of user registration and login generated. However, this is the subject of other lessons.

Creating an article model

We should first start by creating a table for the future article model. We can have the migration generated together with Eloquent models, we will see what options we have for that. To do this, use the help command in the Artisan terminal:

php artisan help make:model

After inserting the command, we will see the following output:

Laravel Framework for PHP

As we can see, we have many options to choose from. Describing them all has no meaning for us yet. We will learn to use most of them gradually. We will now be interested in these two options:

  • --resource - Creates a CRUD controller using model instances. This is a controller for operations to add, view, edit and delete an item, in our case an article.
  • --migration - Generates a migration to create a table of a model. This will also create a database table for the item.

So we will insert the following command to create an article model with these options:

php artisan make:model --resource --migration Article

The migration and controller can also be created separately. The notation above is only a shortening of the following commands:

php artisan make:model Article
php artisan make:migration --create=articles create_articles_table
php artisan make:controller --model=Article ArticleController

The output of the success command looks like this:

Output of the Artisan command for creating models in the Laravel PHP framework - Laravel Framework for PHP

As we can see in the picture above, three required files were generated for us. At first we start with the already mentioned migration to create a table of articles.

Migration of the article table

We will certainly agree that each article must have its own ID, according to which we will identify it, for example, when editing it. At the same time our table will contain the columns created_at and updated_at defining the creation and last modification times. These columns, along with the id, are already included by default in each generated table. In addition, we will now add the title, (unique) URL, content and description of the article.

The migration file for creating a table of articles named ..._create_articles_table.php, which can be found in the database/migrations/ folder, we'll modify to the following form:

<?php

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

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('url')->unique();
            $table->string('description');
            $table->text('content');
            $table->timestamps();
        });
    }

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

Migration files may differ for you by the date in their name. However, this can be used in case we would like some of the migrations to take place earlier. We would only change this date in the file name.

We will now start the migration via the php artisan migrate command, which will result in the creation of a migration database table that holds all ran migrations. Of course, tables of users, reset passwords, articles and failed tasks will also be created:

Launch of the first migration in the PHP framework Laravel - Laravel Framework for PHP

The output may vary based on the creation date of the migrations, which is reflected in their name and which may be modified if necessary. Therefore, the migration with articles is performed before the migration with the table for failed tasks.

Article model

Let's move on to the model. It can be found right in the app/ folder named Article.php. It now only contains the creation of the Article class inheriting from Model. You may be surprised, but at this stage the model is fully functional. All the methods we will need to work with the database (searching, creating, editing) are contained in the Model, which defines the Eloquent ORM.

We do not need to specify the table with which the model works. The names of models are derived from the name of tables, where the table is in the plural of the name of the entity and the model in the singular, because it represents exactly one row of the database table. If for some reason we do not follow this and want a different table name, we can define this name through the variable $table:

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'articles';

Article controller

Now let's look at the generated article controller in the app/Http/Controllers/ folder named ArticleController.php. It already contains CRUD methods for actions of listing articles, creating new ones, editing and deleting:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  Article $article
     * @return Response
     */
    public function show(Article $article)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  Article $article
     * @return Response
     */
    public function edit(Article $article)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request $request
     * @param  Article $article
     * @return Response
     */
    public function update(Request $request, Article $article)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  Article $article
     * @return Response
     */
    public function destroy(Article $article)
    {
        //
    }
}

Typically, these methods are used as follows:

  • index() - Display list of articles (can be used for administration)
  • create() - Display the form for creating an article
  • store() - Create an article from the passed form values
  • show() - Display the article itself
  • edit() - Displays the form for editing the article
  • update() - Modify the database record with the article
  • destroy() - Delete an article from the database

The use of CRUD controllers makes work extremely easy, as their routing is much simpler and at the same time it adds other possibilities when working with a given controller.

In the next lesson, Simple CMS in Laravel - Article listing, we'll see our first article. In addition, you will be able to download the source code in case you have a problem with anything :)


 

Previous article
Simple CMS in Laravel - Project structure
All articles in this section
Laravel Framework for PHP
Skip article
(not recommended)
Simple CMS in Laravel - Article listing
Article has been written for you by Lishaak
Avatar
User rating:
No one has rated this quite yet, be the first one!
Author is interested in programming mostly at web development, sometimes he does funny video edits from his vacations. He also loves memes and a lot of TV series :)
Activities