Laravel API Series: Setup, Database, Migrations, and Models
Tags: laravel, webdev, beginners, tutorial
Published: 2022-03-07 20:36:10

## 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](https://getcomposer.org/) installed.
- Any code editor.  I'll recommend [VSCode](https://code.visualstudio.com).
- Any HTTP client.  I'll recommend [Postman](https://www.postman.com/).
- 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:
```bash
composer global require laravel/installer
```
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:
```bash
laravel new apitutorial
```
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](https://laravel.com/docs/9.x/structure). After that, navigate to the `routes/api.php` and replace the generated route with the following code below like so:
```php
Route::get('/', function () {
    return "Hello World";
});
```
After that, you need to run your application with the web server that comes with Laravel CLI tool (Artisan) like so:
```bash
php artisan serve
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qwjrzzhmd4w1lmi5hywm.png)

- 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](https://www.apachefriends.org/), 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4sab87n72364odwjolqw.png)

After that you need to connect the database to your Laravel application by filling the database details inside your `.env` file like so:
```env
DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
```
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:
```bash
php artisan make:migration create_posts_table
```

> 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:
```php
    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();
        });
    }
```
- 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](https://laravel.com/docs/9.x/migrations#available-column-types) 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:
```bash
php artisan migrate
```
And you should see a response like below in your command like:

![migration successful](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hz9tm5t0sb17smmq0dgz.png)
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:
```bash
php artisan make:migration add_draft_to_posts_table
``` 
> 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:
```php
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->boolean('draft')->default(1);
        });
    }
```
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:
```bash
php artisan migrate
```
 ![successful table update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3azhm5a94v88or7ij49.png)
- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pq8ns6lpcfoljrpr49sn.png)
 
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:

```bash
php artisan make:migration create_authors_table
```
Next, define the table inside the generated file like so:
```php
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->id();
            $table->string('author_name');
            $table->string('author_email');
            $table->timestamps();
        });
    }
```
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:
```bash
php artisan make:model Post
```
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:
```bash
php artisan make:model Author
```
> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikeyja4ugbnj4ld8s3w8.png) 
- 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:
```php
protected $fillable = ['author_id', 'title', 'body', 'likes', 'draft'];
```
> 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:

```php
protected $fillable = ['author_name', 'author_email'];
```
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.