DEV Community

Cover image for Laravel API Series: Setup, Database, Migrations, and Models
Adams Adebayo
Adams Adebayo

Posted on • Originally published at olodocoder.hashnode.dev

Laravel API Series: Setup, Database, Migrations, and Models

Introduction

In this tutorial series, you will learn how to build a blog posts API with user authentication (Sign Up, Login, and Logout) and search functionalities from scratch using Laravel and Laravel Sanctum.

What you'll learn

In this part of the series, you'll learn about the following:

  • The prerequisites to follow along with this series
  • Reasons why you would want to use Laravel
  • Laravel's installer and creating a new project
  • How to setup database
  • What migrations are, and how to create and use them in Laravel
  • Table relationships basics
  • What models are, and how to create and use them in Laravel

Prerequisites

  • Basic knowledge of PHP.
  • Composer installed.
  • Any code editor. I'll recommend VSCode.
  • Any HTTP client. I'll recommend Postman.
  • Basic knowledge of Laravel will be helpful but not required, as I will be explaining every Laravel concept I'll be using in this tutorial.

So why Laravel?

Laravel is one of the most popular PHP frameworks out there, and in my opinion should be the go to option for beginner PHP developers because of four main reasons:

  • It is one of the best frameworks for building modern web applications.
  • It has a really huge ecosystem, so it's easier for new developers to get all support they need.
  • It's main goal is to save you as much development time as possible by providing a lot of the common features you need to implement, so they just work out of the box.
  • Last but not the least, it's syntax is really expressive and elegant.

I hope this tutorial is able to show you how easy it is to work with Laravel.

Project Structure

With the introduction and prerequisites out of the way, let's get started. First you need to have the Laravel installed globally, you can do that using Composer by running the following in your command line:

composer global require laravel/installer
Enter fullscreen mode Exit fullscreen mode

The command above will install Laravel globally on your system so you can run Laravel CLI commands inside any folder on your system. After that's done, you'll need to create a new Laravel project inside your preferred directory, and you can do that by navigating to your command line and running the following command:

laravel new apitutorial
Enter fullscreen mode Exit fullscreen mode

The above command will create a folder named apitutorial which will contain your Laravel project, Next, go through the project and read about the project structure here. After that, navigate to the routes/api.php and replace the generated route with the following code below like so:

Route::get('/', function () {
    return "Hello World";
});
Enter fullscreen mode Exit fullscreen mode

After that, you need to run your application with the web server that comes with Laravel CLI tool (Artisan) like so:

php artisan serve
Enter fullscreen mode Exit fullscreen mode

The above should start your application on port 8000 (You'll see the port it's running on in your command line). Then, open your HTTP client and enter the URL, and add the /api so it'll be localhost:8000/api because it's an API request, and select the GET request to get a response, for me, it'll look like the following in Postman:

success postman request

  • The purple box is the type of request you sent, which is a GET request
  • The green box is the result our server sent back, which is the same as the text we returned inside our route function above.

Now that you have successfully set up the new Laravel project, Next, I'll be going through how to set up the database and use it in your project.

Database Setup

Now that you have successfully set up your project and have written and sent your first API request in Laravel, the next thing is to set up your database, as you are going to need that to store your application data.

I'll be using a MySQL database with PHPMYADMIN that comes with my local installation of XAMPPSERVER, so I'm going to show you how to set that up. First, you need to create a database inside the PHPMYADMIN GUI I'll name mine apitutorial like so:

database creation

After that you need to connect the database to your Laravel application by filling the database details inside your .env file like so:

DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

And that's it! You have successfully connected your MySQL database to your Laravel application. Next, I'll explain what migrations are in Laravel and how to use them in your application.

Migrations

After connecting your database to your application, the next thing is to add tables and columns to the database so you can add rows of data to the database, and I'm going to show you how to do that in this section.

The first thing you need to do is to create a migration file for the table you want to add to the database, but with Laravel's awesome CLI you can easily generate migrations files like so:

php artisan make:migration create_posts_table
Enter fullscreen mode Exit fullscreen mode

Notice the migration name? It's a convention i.e You'll do this if you want to create a books table: php artisan make:migration create_books_table

The above command will generate a file named yyyy_mm_dd_hhmmss_create_posts_table inside the /database/migrations folder, next thing you need to do is define the columns you want inside your posts table, and you do that inside the up function that was generated inside the migrations file, for me it'll look like so:

    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->longText('body');
            $table->integer('likes')->default(0);
            $table->bigInteger('author_id');
            $table->timestamps();
        });
    }
Enter fullscreen mode Exit fullscreen mode
  • The id column is the unique identifier and it will be generated automatically.
  • The title field is the string value of every post title.
  • The body field is the longText value of every post body.
  • The likes field is the number of likes that each post has, which will be 0 for every new post.
  • The author_id is the id of the author of the post.
  • The timestamps is the combination of the created_at and updated_at columns. You can check here for the list of all column types supported in Laravel.

Running your migrations

Once that's done, the next thing is to run your migrations, and you do that by running the following command in your command line:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

And you should see a response like below in your command like:

migration successful
If you see a response like the one above, it means that your migrations ran successfully. Notice that there's more than one migration listed? That's because Laravel created some default migration files when you created the Laravel boilerplate application.

Updating Tables

Inside the up function that I defined above, I forgot to add the draft column which will be a boolean value for determining if a post is still a draft or has been published and the default value will be true.

The first solution that might pop up in your mind might be to go into your database manager and add the column manually, but that's not going to work because that's what migrations are for, they are like version control for your database. So, to update your database with the missing column, the first step is to generate a special type of migration file like so:

php artisan make:migration add_draft_to_posts_table
Enter fullscreen mode Exit fullscreen mode

Note: The naming of the above file is important because it tells Laravel that you want to add a draft to the **posts** table.

This will generate a migration file inside the /database/migrations folder, this file will update your posts table when you run migrations, the next step is to define the column types you would like to add to your table inside the up function in the generated file, mine will look like so:

    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->boolean('draft')->default(1);
        });
    }
Enter fullscreen mode Exit fullscreen mode

The next thing after that is to run the migration for the update, so you run that as you did earlier by running the following command in the command line again:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

successful table update

  • The first command: php artisan make:migration add_draft_to_posts_table generated the file you used to update the table.
  • The second command: php artisan migrate:status is used to check the migrations status, and mine shows that all migrations are done except the update file.
  • The third command: php artisan migrate migrated the update file, so the draft column should be added to the posts table now.

database update confirmation

The above screenshot shows the draft column in the posts table. Next, I'll show you how to connect tables in Laravel.

Table Relationships

Now that you know what migrations are, how to use them to define your database tables, and how to run them to add tables to your database. The next step is to learn how to work with relationships in Laravel, and to do that you need to have two or more tables, so create another migration file called authors like so:

php artisan make:migration create_authors_table
Enter fullscreen mode Exit fullscreen mode

Next, define the table inside the generated file like so:

    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->id();
            $table->string('author_name');
            $table->string('author_email');
            $table->timestamps();
        });
    }
Enter fullscreen mode Exit fullscreen mode

Next, run the authors migration so the authors table gets created inside your database. In order to connect the posts table and the authors table, you need to first understand some more concepts in Laravel. So I'll continue the table relationships in a later section. Next, let's see how to use models in Laravel.

Models

Eloquent models, also commonly referred to as models, is an object relational mapper (ORM) that is used to create, read, update and delete records in your database tables in Laravel.

Creating models

To create a model in Laravel, run the following command in the command line:

php artisan make:model Post
Enter fullscreen mode Exit fullscreen mode

You need to create a model for each migration file you have, so you'll run the command again for the authors migration, like so:

php artisan make:model Author
Enter fullscreen mode Exit fullscreen mode

Notice the use of capital letter for the first letter and singular word? that's because the model is a class and class names always starts with a capital letter.

Generate Models

  • The first command created the Post model.
  • The second command created the Author model.
  • Both files will be inside /app/Models folder.

Adding fillable array

The $fillable is an array containing the columns you want to allow mass assignments(sending array of data to create a record in the database) for inside your database, you need to add the $fillable array inside each of your model files. The author $fillable array will look like so:

protected $fillable = ['author_id', 'title', 'body', 'likes', 'draft'];
Enter fullscreen mode Exit fullscreen mode

Notice that the array contained every column in the posts migration file except the id and the timestamps as those will be generated automatically. Remember, you need to add the $fillable array inside all your model files, so your author's $fillable array should look like so:

protected $fillable = ['author_name', 'author_email'];
Enter fullscreen mode Exit fullscreen mode

Now that you have added the $fillable array inside your model files, you are ready to create, read, update , and delete data inside your database.

Recap

So far, you've seen how to do the following:

  • Create a new Laravel application.
  • Setup the database.
  • Create and run migrations.
  • Basics of table relationships.
  • Create models and add the fillable array.

In the next part, I'll show you how to work with, Controllers, Routing, Resource routes, and adding extra functionalities to the controller file (in my case search()) in Laravel.

Top comments (0)