
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
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
After migrating into your project with the above command, run the next command below.
composer install
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=
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.
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
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
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(); }); }
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');
After completing the above, run migration tomigrate/create
your tablecontact
on your database.
php artisan migrate
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');
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();});
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
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}
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); } }
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.
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 }
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); } }
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.
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" } ]
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); } }}
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'); }};
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();});
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)
For further actions, you may consider blocking this person and/orreporting abuse