DEV Community

Cover image for Building REST API with Laravel 9x
Noble Okechi
Noble Okechi

Posted on

Building REST API with Laravel 9x

Laravel is a PHP framework that is build for web Artisan. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching.

Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality.

Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.

Laravel is a backend framework that provides all of the features you need to build modern web applications, such as routing, validation, caching, queues, file storage, and more. However, we will be learning steps on how to build REST API with Laravel 9x.

Laravel 9 continues the improvements made in Laravel 8.x by introducing support for Symfony 6.0 components, Symfony Mailer, Flysystem 3.0, improved route:list output, a Laravel Scout database driver, new Eloquent accessor / mutator syntax, implicit route bindings via Enums, and a variety of other bug fixes and usability improvements.

Laravel 9 has been one of the most prevalent PHP frameworks for a long time now. It is adaptable, scalable, versatile, and has become one of the in fact the systems for engineers and companies working with PHP.

Contents

  • Prerequisites
  • Create a Laravel Project
  • Setup a Database
  • Create a Database Migration
  • Create an API Routes
  • Create a Controller
  • Code your Functions
  • Code Modules
  • Conclusion

Prerequisites

To follow along with this tutorial, you need to ensure that PHP and Composer is installed on your local computer for artisan commands. If you are building frontend on a same file, I recommend you install Node for NPM commands. But for this content, we shall be using Postman for testing and I recommend you to go through my content on how to setup postman with laravel.

Create your Laravel Project

To create a laravel project, run the commands below

composer global require laravel/installer

laravel new laravel-9x
Enter fullscreen mode Exit fullscreen mode

composer is a dependency manager for PHP that provides a standard format for managing dependencies of PHP software and required libraries.

The first command composer global require laravel/installer is used to install laravel on your local machine.

laravel new laravel-9x command installs a fresh laravel project on your computer.

Note: laravel-9x can be replace with any preferred name of your choice, as it serves as the project name.

After the project has been created, cd into the project directory.

cd laravel-9x
Enter fullscreen mode Exit fullscreen mode

After migrating into your project with the above command, run the next command below.

composer install
Enter fullscreen mode Exit fullscreen mode

The above command creates a new vendor folder on our project and gives access to run to run artisan commands.

Setup a Database

To setup your database on laravel, locate .env file inside your project files.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testproject
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

For this project, I will be using MySQL database and that is while I have the above code snippet.

DB_DATABASE=testproject represents your database file name, which testproject can be changed to any preferred name of your choice.

Image description

Having created a database connection as shown above, you can run the below command to migrate your database model.

php artisan key:generate

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

The command above generate an APP_KEY on the .env file for your project, while the second command migrate your database.

Create a Database Migration

A migration file in laravel represents a database table file in the core PHP code. Migration file is often generated according preferred name of your database table.

We will generate a migration file called contact, which will serve as contact table for testing our REST API.

php artisan make:model Contact -m
Enter fullscreen mode Exit fullscreen mode

The above command will generate a model and database migration file called contact.

Locate the migration inside your project on database/migrations/2022_09_16_042805_create_contacts_table.php. Note that the file name is been named with the current data attached to it.

public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('tel');
            $table->timestamps();
        });
    }
Enter fullscreen mode Exit fullscreen mode

Copy and replace the up() function with the snippet above.

Note, we only added the code block below to the function up()

$table->string('name');
$table->string('email');
$table->string('tel');
Enter fullscreen mode Exit fullscreen mode

After completing the above, run migration to migrate/create your table contact on your database.

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Create an API Routes

In laravel, we can register all our API routes inside routes/api.php file.

We will be registering two post API routes before the middleware routes function. We are creating save_data and fetch_data routes.

Route::post('save_data', [ContactController::class, 'save_data'])->name('api.save_data');
Route::post('fetch_data', [ContactController::class, 'fetch_data'])->name('api.fetch_data');
Enter fullscreen mode Exit fullscreen mode

The above code block demonstrate how your route should lock like.

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;


Route::post('save_data', [ContactController::class, 'save_data'])->name('api.save_data');
Route::post('fetch_data', [ContactController::class, 'fetch_data'])->name('api.fetch_data');

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Enter fullscreen mode Exit fullscreen mode

This is my entire api.php route file codes, you can copy and replace with yours.

Create a Controller

Controllers can group related request handling logic into a single class.
A Controller is that which controls the behavior of a request. It handles the requests coming from the Routes. In Laravel, a controller is in the app/Http/Controllers directory.

We will have to create a controller named ContactController using the command below.

php artisan make:controller ContactController
Enter fullscreen mode Exit fullscreen mode

After creating our controller, we can locate the controller on app/Http/Controllers.

Code your Functions

This is the sweetest part of this article is the coding aspect, here can write your codes according your coding preference, but for a better clarity, you can make reference to my codes.

Inside the ContactController.php, we will be having two functions according to our routes on routes/api.php, where we have save_data and fetch_data routes.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
    // code here
}
Enter fullscreen mode Exit fullscreen mode

The above code block, represents everything in our ContactController.php before we write our functions inside.

Now, we will be writing our first function, which is the save_data function.

 public function save_data(request $request)
    {
        if(isset($request->name) && isset($request->email) && isset($request->tel)){
            // proccess data
            $contact = new contact;
            $contact->email = $request->email;
            $contact->name = $request->name;
            $contact->tel = $request->tel;
            if ($contact->save()) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Data saved successfully',
                    'data' => $contact
                ]);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'An error occured'
                ],500);
            }

        }else{
            return response()->json([
                'status' => 'error',
                'message' => 'Missing Paramiter'
            ],501);
        }
    }
Enter fullscreen mode Exit fullscreen mode

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists.

The above code block will save data coming from our REST API routes into our contact model in the database.

For this article, I will be testing with postman, if you are new to postman, I will suggest you check this article on how to setup postman with laravel.

From postman, we will be sending name, email, and tel as required on the save_data function.

Image description

If you have sent the exact data as mine on the snapshot above, you will be getting same response as mine.

"status": "success",
    "message": "Data saved successfully",
    "data": {
        "email": "okechinoble@gmail.com",
        "name": "Noble Okechi",
        "tel": "+2349097784784",
        "updated_at": "2022-09-16T14:47:45.000000Z",
        "created_at": "2022-09-16T14:47:45.000000Z",
        "id": 1
    }
Enter fullscreen mode Exit fullscreen mode

Now, that we have achieved the save_data function, it is time to work build our fetch_data function for getting all stored data from contact model.

public function fetch_data()
    {
        $fetch = contact::latest()->get();
        if ($fetch) {
            return response()->json([
                'status' => 'success',
                'message' => 'Data fetched successfully',
                'data' => $fetch
            ]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occured'
            ],500);
        }

    }
Enter fullscreen mode Exit fullscreen mode

latest() fetches the most recent set of data from the Database. it sort its data using the created_at column.

Now, we can create fetch_data request on postman to test the fetch_data function.

Image description

After setting up postman request to fetch data from fetch_data API, I got an array of data as response below.

"status": "success",
    "message": "Data fetched successfully",
    "data": [
        {
            "id": 2,
            "name": "Developer Noble",
            "email": "dev@gmail.com",
            "tel": "+234000000000",
            "created_at": "2022-09-16T15:20:39.000000Z",
            "updated_at": "2022-09-16T15:20:39.000000Z"
        },
        {
            "id": 1,
            "name": "Noble Okechi",
            "email": "okechinoble@gmail.com",
            "tel": "+2349097784784",
            "created_at": "2022-09-16T14:47:45.000000Z",
            "updated_at": "2022-09-16T14:47:45.000000Z"
        }
    ]
Enter fullscreen mode Exit fullscreen mode

Wow, if you have gotten it to this extent, bravos.

Code Modules

We can now wrap up our code by posting the entire codes module by module.

ContactController Module

ContactController module is located at app/Http/Controllers

<?php

namespace App\Http\Controllers;

use App\Models\contact;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function save_data(request $request)
    {
        if(isset($request->name) && isset($request->email) && isset($request->tel)){
            // proccess data
            $contact = new contact;
            $contact->email = $request->email;
            $contact->name = $request->name;
            $contact->tel = $request->tel;
            if ($contact->save()) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Data saved successfully',
                    'data' => $contact
                ]);
            } else {
                return response()->json([
                    'status' => 'error',
                    'message' => 'An error occured'
                ],500);
            }

        }else{
            return response()->json([
                'status' => 'error',
                'message' => 'Missing Paramiter'
            ],501);
        }
    }

    public function fetch_data()
    {
        $fetch = contact::latest()->get();
        if ($fetch) {
            return response()->json([
                'status' => 'success',
                'message' => 'Data fetched successfully',
                'data' => $fetch
            ]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occured'
            ],500);
        }

    }
}

Enter fullscreen mode Exit fullscreen mode

Contact Migration Module

If you can recall, we buildup our database contact model fields inside migration folder and can be located at database/migrations.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('tel');
            $table->timestamps();
        });
    }

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

Enter fullscreen mode Exit fullscreen mode

API Routes Modules

API routes is located at routes/api.php.

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;


Route::post('save_data', [ContactController::class, 'save_data'])->name('api.save_data');
Route::post('fetch_data', [ContactController::class, 'fetch_data'])->name('api.fetch_data');

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Enter fullscreen mode Exit fullscreen mode

Conclusion
In this article, we successfully explored different modules in laravel 9x and we demonstrated easy steps on how to build REST APIs on laravel 9x.

With laravel 9x, it is easy to build standard REST APIs for every frontend.

Top comments (0)