Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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, improvedroute: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 andComposer is installed on your local computer forartisan commands. If you are building frontend on a same file, I recommend you installNode for NPM commands. But for this content, we shall be using Postman for testing and I recommend you to go through my content onhow to setup postman with laravel.

Create your Laravel Project

To create a laravel project, run the commands below

composer global require laravel/installerlaravel new laravel-9x
Enter fullscreen modeExit 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 commandcomposer global require laravel/installer is used to installlaravel 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 modeExit fullscreen mode

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

composer install
Enter fullscreen modeExit fullscreen mode

The above command creates a newvendor folder on our project and gives access to run to runartisan commands.

Setup a Database

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

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=testprojectDB_USERNAME=rootDB_PASSWORD=
Enter fullscreen modeExit fullscreen mode

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

DB_DATABASE=testproject represents your database file name, whichtestproject 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:generatephp artisan migrate
Enter fullscreen modeExit fullscreen mode

The command above generate anAPP_KEY on the.env file for your project, while the second commandmigrate your database.

Create a Database Migration

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

We will generate a migration file calledcontact, which will serve as contact table for testing ourREST API.

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

The above command will generate amodel and database migration file calledcontact.

Locate the migration inside your project ondatabase/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 modeExit fullscreen mode

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

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

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

After completing the above, run migration tomigrate/create your tablecontact on your database.

php artisan migrate
Enter fullscreen modeExit fullscreen mode

Create an API Routes

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

We will be registering twopost API routes before themiddleware routes function. We are creatingsave_data andfetch_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 modeExit fullscreen mode

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

<?phpuse 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 modeExit fullscreen mode

This is my entireapi.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 theapp/Http/Controllers directory.

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

php artisan make:controller ContactController
Enter fullscreen modeExit fullscreen mode

After creating our controller, we can locate the controller onapp/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 theContactController.php, we will be having two functions according to our routes onroutes/api.php, where we havesave_data andfetch_data routes.

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class ContactController extends Controller{    // code here}
Enter fullscreen modeExit fullscreen mode

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

Now, we will be writing our first function, which is thesave_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 modeExit fullscreen mode

Theisset() 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 ourcontact model in the database.

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

From postman, we will be sendingname,email, andtel as required on thesave_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 modeExit fullscreen mode

Now, that we have achieved thesave_data function, it is time to work build our fetch_data function for getting all stored data fromcontact 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 modeExit fullscreen mode

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

Now, we can createfetch_data request on postman to test thefetch_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 modeExit 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 atapp/Http/Controllers

<?phpnamespace 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 modeExit fullscreen mode

Contact Migration Module

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

<?phpuse 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 modeExit fullscreen mode

API Routes Modules

API routes is located at routes/api.php.

<?phpuse 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 modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

The captions of my goal is to contribute immensely towards developments/improvements and to see that efficiency and reliability won't be left behind.
  • Education
    Graduate of Computer Science
  • Work
    Fullstack Engineer
  • Joined

More fromNoble Okechi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp