How to Build a REST API in Laravel 6.0

This tutorial is aimed at complete beginners, so, the API we’ll be building will be as barebones as possible. This tutorial assumes you’re already on the correct file path and you have composer installed on your machine. Also, basic PHP and MVC knowledge are required to understand what’s going on over here. 

If you don’t know what’s new with Laravel 6.0 and you’d like to familiarise yourself with the recent changes, I would recommend taking a look here.

Installation

First off, you’re gonna wanna open your terminal and run the following command to install the Laravel installer:

composer global require laravel/installer

If you managed to install the Laravel installer correctly, you can now run the following to create a Laravel project with the name of your choice. Afterward, change directory and check if all the default folders and files are all there:

laravel new test_api

cd test_api

ls

Before we move any further, check if you’re connected to your web server by running this command (will only work if you have PHP installed):

php artisan serve

Setting up your Environment

Next, you need to specify the correct environment credentials in your .env file. The app key should have already been generated since we installed Laravel via the Laravel installer. There should only be two variables you need to update if you have your app key. Change ‘DB_DATABASE’ to equal the name of the database you want to create. Then, update your ‘DB_PASSWORD’ to equal your MySQL password.

Before creating the migrations, we need to create an empty database so the migrations know where to go. It may well be easier for you to use an interface such as PHPMyAdmin or Sequel Pro to create your database. But if you want to use the command line. Here are the following commands to log in to MySQL, create a database, and display the database:

mysql -u root -p

CREATE DATABASE test_api;

SHOW DATABASES;

Migrations

a group of migrating penguins

Next up, migrations. Before creating any of my own migration files, I like to check if I need the default migration files that come with Laravel. If I don’t, I delete them. They’re located under database/migrations. This is also where your created migration files will appear. After you’ve decided whether to keep those files or delete them, it’s time to create your migration file(s) and table(s). For simplicity’s sake, I’ll be creating a single migration file.

php artisan make:migration create_employees_table --create=employees

If you didn’t know, the –create flag in the command will specify the name of the table you want to create. Once that’s done, locate your migration file(s) under database/migrations. You’ll now see two methods in your class. up() will push your data ‘up’ into the database. down() will take your data ‘down’ from the database. Under the up() method, you’ll want to specify the names and formats of the columns you want in the table(s) of your database. This is how mine looks:

public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique(); 
            $table->date('start_date');
            $table->date('due_date'); 
        });
    }

Once you’re happy with the way your migration file(s) looks, you can run the migration.

php artisan migrate

Before moving further, it would be a good idea to return to your MySQL prompt in the terminal and check if your columns are structured in the way you want them to be. Or check with PHPMyAdmin or Sequel Pro.

USE test_api;

SHOW TABLES;

SHOW COLUMNS FROM employees;

Filling up the Database

a woman planting seeds on a summer's day

Seeding is a very useful and simple solution to put data into the database quickly. It’ll save you a lot of time and energy manually inserting data into the database. First of all, you’ll want to create your seeding file(s). For example, if the table you want to seed is called ’employees’, then your command would look like this:

php artisan make:seeder EmployeesTableSeeder

While seeding the database is a quick method to insert data into the database. Factories save you a lot of time and energy specifying the values for each model seed. To make a factory and connect it to the model you’ll create immediately after, run the following (use the singular, not plural, for the naming of your factory):

php artisan make:factory EmployeeFactory --model=Employee

Then create your model.

php artisan make:model Employee

If you followed the previous commands, the model will already be linked to the seeder and factory files.

You now have all the necessary files for populating your database. Before we mover further, if you did delete the migration files you didn’t want earlier, follow this next step. If you kept them, you can skip to the part where we edit the factory file(s). To prevent you from getting a PDO exception SQL state error about unfound columns, enter the following under your class in your model(s):

// prevents SQLSTATE[42S22] 'Column not found' error
    public $timestamps = false;

Now go to your factory file(s) located under database/factories. Here is where you’ll define the values of each column by using the Faker PHP library. Faker is a really handy tool for providing ‘fake’ data. Except, the data is realistic. For example, if you provide names from the Faker library, these will be real names such as ‘John Smith’, not just a random string of characters. In this file, you’ll see one method, edit it so it returns the data you want to insert into your database. For example, I have four columns I wish to insert data into. Therefore, my method will look like this:

$factory->define(Employee::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique->companyEmail,
        'start_date' => $faker->date,
        'due_date' => $faker->date 
    ];
});

If you’re not sure which Faker data types your columns require, you may be able to find them here: https://github.com/fzaninotto/Faker.

Now that your factory has been defined, you can now edit your seeder files. Find the seeder file you created first. Mine will be called EmployeesTableSeeder which is located under database/seeds. It’ll have one method called run(). This method will be called upon whenever you run your seed in the command line. Which we’ll do very soon.

public function run()
    {
        factory(App\Employee::class, 50)->create();
    }

The number in your method will specify the number of rows you would like in your table (in my case, 50).

Once you’ve done that, switch over to your DatabaseSeeder.php file and comment out the method. All you’ll have to do is make sure it calls your seeder.

public function run()
    {
        $this->call(EmployeesTableSeeder::class);
    }

Finally, you can seed your database:

php artisan db:seed

To see if everything worked as expected, check your database on PHPMyAdmin or Sequel Pro.

data displayed in phpmyadmin for the api

Well, maybe the names aren’t exactly like ‘John Smith’.

Fetching the Data

a brown, black, and white dog carrying a stick on the grass

OK, so, we have some data to work with. To fetch and structure that data, we first need to create our controller(s):

php artisan make:controller EmployeeController --resource

Notice the –resource flag. By including this in your command you’ll automatically get the necessary HTTP methods within your controller class. So, you’ll want to include this. However, for the sake of this tutorial, my API will be especially simple, so I’m gonna delete all the methods except ‘index()’.

Before we start tinkering with anything else, let’s visit ‘routes/api.php’ and set up the routes which will enable us to connect to our controller(s). The number of routes you’ll have will depend on how many controller methods you have. I’m only using ‘index()’, so, I’ll only need to add one route:

Route::get('employee', '[email protected]');

Next, we need to make our resource file(s). This is what will determine which columns we’ll retrieve from the database and what they’re labeled with. For example, if we wanted to retrieve the ID from each row, and label them ‘id’, we would return this:

'id' => $this->id

‘id’ is the label and ‘$this->id’ is the actual ID retrieved from the database.

I wish to retrieve all the columns from my only table in the database. So, my method looks like this:

public function toArray($request)
    {
        return [
            'id' => $this-id,
            'name' => $this->name,
            'email' => $this->email, 
            'start_date' => $this->start_date,
            'due_date' => $this->due_date
        ];
    }

Almost finished now. Let’s move over to the controller file(s) in ‘app/Http/Controllers’. These will have all the methods that were created with ‘–resource’. Unless, like me, you decided to delete all the ones you didn’t need. In this tutorial, I’m only going to edit the index file just so we can fetch the data. Before we do that though, let’s connect to the model(s) and the resource(s) by adding the following above your class:

use App\Employee; // connects to the model

use App\Http\Resources\Employee as EmployeeResource; // connects to the resource file 

When connecting to the resource file above, you’ll notice that we use ‘Employee as EmployeeResource’ even though the resource file in this particular case would be called ‘Employee.php’, so we would reference it as ‘Employee’ right? The problem is that the model is also called ‘Employee.php’, so we reference that as ‘Employee’ beforehand. We can’t reference them both as the same name as this would cause conflict. Try it and your text editor will throw you a warning and tell you the reference already exists.

Under the ‘index()’ method, I’m going to add two lines of code. The first line will specify the pagination (how many rows of data I want to appear on each page, for me it will be 10). The second line will take the resource we created and simply return it as a collection.

public function index()
    {
        $employees = Employee::paginate(10);
        
        return EmployeeResource::collection($employees);
    }

Viewing the Data

the postman api logo

You have two options when attempting to view your data. One of the options would be simply entering your URL into the browser. However, your data would come back looking something like this:

Meh. Or, you can use an API development platform such as Postman to view your data:

api data displayed in postman

Much better.

If you’re unsure about how to enter your URL, you should enter the domain or IP address, then ‘api’, then the name of your resource:

http://127.0.0.1:8001/api/employee

CORS Configuration

This is the last thing we need to do. Without CORS (Cross-Origin Resource Sharing) configuration, you won’t be able to connect to the API you just made with a front-end application. If you want to know more about CORS, I would suggest checking out this video. If you have a hard time with Indian accents, you can check out this rather long explanation here.

There are lots of tutorials for CORS configuration out there, but most of them won’t work with Laravel 6.0. Luckily, this method I’m about to show you doesn’t take long and is fairly simple.

First, you’re gonna wanna install a package from https://github.com/barryvdh/laravel-cors.

composer require barryvdh/laravel-cors

After that installation, jump to config/app.php and add this line of code at the bottom of the ‘providers’ array:

Barryvdh\Cors\ServiceProvider::class,

After adding that, visit app/Http/Kernel.php and add this line of code at the bottom of ‘protected middleware’:

\Barryvdh\Cors\HandleCors::class,

Finally, run this command:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

OK, now you’re all set!

Feel free to use the example API I built during this tutorial here.

Thanks for reading.

3 thoughts on “How to Build a REST API in Laravel 6.0”

  1. Pingback: How to Build a REST API in Laravel 6.0 - Harrison Greeves - Rubin Shrestha

Leave a Reply

Your email address will not be published. Required fields are marked *