Laravel

How To Create Rest API Using Lumen 8

This RestApi tutorial will show you how to use Lumen with MySQL to develop a CRUD REST API. The rest API tutorial uses the Lumen micro-rest framework to read, add, update, and delete records.

I’m building a model with Eloquent ORM to enable Lumen to interact with MySQL for database operations.

Rest Web services are a popular way for clients and servers to connect. There are numerous front-end JavaScript frameworks that communicate with the server via web services. Lumen-micro framework is a PHP-based API micro-framework created by Laravel.

The Video Tutorial

Lumen CRUD Rest API Using MySQL

Let’s create a lumen project using composer and start a development environment for the lumen project.

Install Lumen by issuing the Composer create-project command in your terminal:

composer create-project --prefer-dist laravel/lumen customers

Start PHP development server:

php -S localhost:8000 -t public

In this tutorial, we’ll go over the following topics:

  • Create Database connection in Lumen with MySQL
  • Migrating table into database using Lumen
  • Get records from MySQL database table using Eloquent Model
  • Create Add,edit and delete Rest API call

How to connect MySQL with Lumen

The Lumen framework makes connecting to the database is very simple. The .env file in Lumen is used to set the application’s global level environment parameters. Please do not upload this .env file to a version control system such as GIT or SVN. All application-level credentials will be stored in this file.

Let’s update MySQL database configuration into .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

The parameters are:

DB_HOST: The database hostname.
DB_DATABASE: This is MySQL database name.
DB_USERNAME: The username of MySQL database.
DB_PASSWORD: The password of MySQL database.

Related Post

Created a ‘test’ database into the mysql server and run below query to create ‘customers’ table :

CREATE TABLE `customers` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`id`);

You need to uncomment the below lines in the test_lumen/bootstrap/app.php file, if already un-commented below lines, please skip this step.

$app->withFacades();
$app->withEloquent();

How to efine Model into Lumen 8

A Model helps to query data to and from the table in the database. Lumen is using Eloquent ORM (Object Relational Mapping) to interact with the table. Let’s create a Eloquent model file 'Customer.php' under app/Models/ folder.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model {
   protected $fillable = ['id', 'name', 'address', 'phone'];
   protected $table = 'customers';
}

in the above model file, We have defined MySQL table field names that will use to get, insert and edit records.

Lumen API Routes

We’ll construct CRUD operation routes in the lumen framework’s routes/web.php file for application routes configuration.

$router->group(['prefix' => 'api/v1/'], function () use ($router) {
    $router->get('customers', 'CustomerController@all');
    $router->post('customer', 'CustomerController@createCustomer');
    $router->get('customer/{id}', 'CustomerController@getById');
    $router->put('customer/{id}', 'CustomerController@updateCustomer');
    $router->delete('customer/{id}', 'CustomerController@deleteCustomer');
});

Action Method in Laravel 8

Let’s get started by making a CustomerController.php file. This file is in charge of all action methods, including getting all records, getting a single record, adding a new record, updating an existing record, and deleting an existing record.

Get All Records from MySQL Table

We’ve put all of the essential helper classes and customer models at the front of the project. Using lumen and the Eloquent ORM all() method, I created an all() method to get entries from a MySQL database.

<?php

namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class CustomerController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */    public function __construct()
    {
    }
    
    //rerurn all customers from mysql table
    public function all() {
        return Customer::all();
    }
}

Get a Record from MySQL Table

Using the elegant eloquent() method, you can get a single record from MySQL. I’ve supplied $id as a parameter, which indicates which record to get.

/**
     * Retrieve the customer for the given ID.
     *
     * @param  int  $id
     * @return Response
     */    public function getById($id)
    {
        return Customer::findOrFail($id);
    }

Create a Record from MySQL Table

We’ll use the lumen Validator class to validate data and pass payloads as a parameter. We’ll use the eloquent create a function to insert the record after successful validation.

/**
     * Create a new record.
     *
     * @return void
     */    public function createCustomer(Request $request)
    {
        $response = array();
        $parameters = $request->all();

        $rules =  array(
            'name'    => 'required'
        );
        $customer_name = $parameters['name'];
 
        $messages = array(
            'name.required' => 'name is required.'
        );
 
        $validator = \Validator::make(array('name' => $customer_name), $rules, $messages);
        if(!$validator->fails()) {
            $response = Customer::create($parameters);
            
            return response()->json($response, 201);
        } else {
         $errors = $validator->errors();
            return response()->json(["error" => 'Validation error(s) occurred', "message" =>$errors->all()], 400);
      }
    }

Update an Existing Record Using Lumen 8

Validate payloads and check whether or not a record exists in the MySQL database table, then update the record in the MySQL table.

public function updateCustomer($id, Request $request)
    {
        $response = array();
        $parameters = $request->all();

        $rules =  array(
            'name'    => 'required'
        );
        $customer_name = $parameters['name'];
 
        $messages = array(
            'name.required' => 'name is required.'
        );
        $cust = Customer::findOrFail($id);
        if(empty($cust)) {
            return response()->json(["error" => 'Record not found!'], 400); 
        }

        $validator = \Validator::make(array('name' => $customer_name), $rules, $messages);
        if(!$validator->fails()) {
            $response = $cust->update($parameters);
            
            return response()->json(['status' => $response, "message" => "Record has been updated successfully."], 200);
        } else {
         $errors = $validator->errors();
            return response()->json(["error" => 'Validation error(s) occurred', "message" =>$errors->all()], 400);
      }
      
    }

Delete a Record from MySQL Table Using Lumen 8

We’ll pass the ‘id’ of the target record as a parameter, check whether the record exists in the customers table, and then delete the record from the MySQL table. For the no record found exception, ModelNotFoundException was created.

public function deleteCustomer($id)
    { 
        try {
            $resp = Customer::findOrFail($id)->delete();
            return response(['status' => $resp, "message" =>'Record has been deleted Successfully'], 200);
        } catch(ModelNotFoundException $e) {
            return response(['status' => 'error', "message" => $e->getMessage()], 200);
        }
        
    }

Conclusions:

We have created a lumen project and added CRUD operations using the rest API endpoints. The rest API help to get all records, add a record, update a record and delete a record.

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

4 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

10 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

10 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

10 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

11 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

11 months ago

Categories