Create REST API Example Using Lumen Micro Framework by Laravel

Rest Web service is very popular service to communicate between client and server.There are a lot of front-end JavaScript framework available which is using web services to communicate with server. Lumen-micro framework is fast and light weight api micro-framework by Laravel using php.
This Lumen tutorial help to create Add,edit and delete rest api call using Lumen. I am using Eloquent ORM to create model that help to communicate mysql with Lumen for database related operation.

I am creation own api rest end points which will insert record into mysql database and edit record on database.You can also delete record from mysql database using lumen rest call.

lumen-micro framework

We will gone through following points in this tutorial,

  1. Create Database connection in Lumen with MySQL
  2. Migrating table into database using Lumen
  3. Get records from mysql database table using Eloquent Model
  4. Create Add,edit and delete Rest API call

How to connect MySQL with Lumen

Its very easy and simple to connect database with lumen framework.Lumen had .env file which is use for set global level environment parameters for Lumen application. Please make sure do not upload this .env file on version control repository like GIT, SVN etc.

This file will contains all application level credential. You can also define mysql connection information into config/database.php file, but this file will available to all public users, as a security concern nobody wants to share connection information to any public users.We will open .env file which is located on route of your project test_lumen/.env.

Select Code
1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=test123

As you can see mysql connection information,The parameters are,
DB_CONNECTION : This will contain database driver information,like mysql,oracle etc.I am using mysql.
DB_HOST : This will contain hostname of database like, IP address or hostname, if your lumen application code and mysql server on same machine.You can define localhost as a hostname.
DB_DATABASE : The name of database.You can replace as per your db name.
DB_USERNAME : The username of mysql database.
DB_PASSWORD : The password of mysql database.

How To Enable eloquent in Laravel/Lumen

The Eloquent is popular and popular ORM(Object-relational mapping), by default Lumen and laravel providing support for that, we just need to enable Eloquent by un-commenting line in test_lumen/bootstrap/app.php file.Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records,edit record and delete record from the table.

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

Select Code
1
2
$app->withFacades();
$app->withEloquent();

Migration

Migration is automated process of database integration with application.There are many CMS and framework using Migration to migrate database tables.We will create two table and both tables has associated records using foreign-key.

Select Code
1
2
php artisan make:migration create_user_views_table –create=user_views
php artisan make:migration create_user_view_details_table –create=user_view_details

Above command will create two tables file under "test_lumen/database/migration" folder.You need to open those file and look into these file,You can see there are two methods already create one "up()" for create table schema and another is "down()" which will use drop the table at the time of rollback.

We will put below code into create_user_views_table file,This will create user_views table into database.

Select Code
1
2
3
4
5
6
7
Schema::create('user_views', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
	$table->string('created_by');
	$table->string('updated_by');
         $table->timestamps();
    });

After make change in above file,The create_user_views_table file will look like below,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php

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

class CreateUserViewsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_views', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('created_by');
            $table->string('updated_by');
            $table->timestamps();
        });
    }

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

We will put below code into create_user_view_details_table file,This will create user_view_details table into database.

Select Code
1
2
3
4
5
6
7
8
Schema::create('user_view_details', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('view_id')->unsigned();
			$table->string('service_name');
			$table->string('created_by');
			$table->string('updated_by');
            $table->timestamps();
        });

Now we will define referential integrity with first one table,We will add below php code before closing tag of "up()" method into create_user_view_details_table file,

Select Code
1
2
3
Schema::table('user_view_details', function($table) {
		   $table->foreign('view_id')->references('id')->on('user_views');
	   });

Once you have done changes in create_user_view_details_table file the whole file code look like below,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

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

class CreateUserViewDetailsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_view_details', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('view_id')->unsigned();
            $table->string('service_name');
            $table->string('created_by');
            $table->string('updated_by');
            $table->timestamps();
        });
        Schema::table('user_view_details', function($table) {
           $table->foreign('view_id')->references('id')->on('user_views');
       });
    }

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

So whenever you will run migrate command on any server this will create user_views and user_view_details tables into database, You don’t need manual interaction to create table into database.

The migrate command is :

php artisan migrate

How to define Model into Lumen/laravel 5

We will create userviews and userviewdetails models file into app/Models/ folder, If you don’t find Models folder please create new one.We will create UserViews.php file and paste below code into them.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class UserViews extends Model {
   protected $fillable = ['name', 'created_by', 'updated_by'];
   protected $table = 'user_views';

   public function UserViewDetails()
    {

        return $this->hasMany('App\Models\UserViewDetails', 'view_id', 'id');
    }

}

Here we have define column name which will use to insert/edit records and will send data from server side.create_on and updated_on column value will automatically insert using current server time, you don’t need to send those col value to server.

We have create hasMany relation with UserViewDetails model to get records from user_wiew_details table.We have passed column name as well for foreign key raltion, where view_id column is foreign key into user_view_details table and id is primary key of user_views table.

We will create UserViewDetails.php file paste below code into this file.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class UserViewDetails extends Model {
   protected $fillable = ['view_id', 'service_name', 'created_by', 'updated_by'];
   protected $table = 'user_view_details';

   public function UserViews()
    {

        return $this->hasOne('App\Models\UserViews', 'id', 'view_id');
    }

}

Now we will create some routes into routes.php file which is located in app/Http folder.The Rest API end points are as follows,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//get all user defined views
$app->get('user_views/{id}', 'UserViewsController@getAllUserViews');

   //create user view
   $app->post('createUserView', 'UserViewsController@createUserView');

   //get user view by ID
   $app->get('user_view/{id}', 'UserViewsController@getUserViewById');

   //update user view
   $app->post('saveUserView', 'UserViewsController@saveUserView');
    
   //delete user view
   $app->delete('delete_view/{id}', 'UserViewsController@deleteUserView');

as you can see, I have writen single line comment on each route which are describing rest call what they will do.

Now we will create UserViewsController.php file and write below code,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

namespace App\Http\Controllers;

use Log;
use Illuminate\Http\Request;
use Jenkinsmgmt\Helpers\Helper;
use App\Http\Controllers\JenkinsController;
use Validator;
use App\Models\UserViews;
use App\Models\UserViewDetails;

class UserViewsController extends Controller {
}

Get all records from Mysql Database Using Lumen and Eloquent

We will create new method getAllUserViews() into UserViewsController.php file and return results.This method will get all user views and corresponding details from userviews and userviewsdetails table.

Select Code
1
2
3
4
5
6
7
public function getAllUserViews(Request $request) {
      $user_views  = UserViews::with('UserViewDetails')->get();
      if(!empty($user_views)) {
         return response()->json($user_views);
         
      }
   }

Get Single record from Mysql Database Using Lumen and Eloquent

We will create new method getUserViewById() into UserViewsController.php file.This method will take view id as a parameters and return view information.I have use Lumen \Validator class to validate view id.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
    * Method to get View by id
    *
    * @author parvez.alam
    */
   public function getUserViewById(Request $request, $id) {
      
      $rules =  array(
            'id'    => 'required'
        );
        
        $messages = array(
            'id.required' => 'id is required.'
        );
      
      $validator = \Validator::make(array('id' => $id), $rules, $messages);

      if(!$validator->fails()) {

         $user_views  = UserViews::with('UserViewDetails')->where('id', $id)->get();//

        return response()->json($user_views);
      } else {
            $errors = $validator->errors();
            return response()->json($errors->all());
      }
   }

Create record into Mysql Database Using Lumen and Eloquent

We will create new method createUserView() into UserViewsController.php file.This method is post type and will create new record into MySQL.You need to send data into json format.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
    * Method to save user View
    *
    * @author parvez.alam
    */
   public function createUserView(Request $request) {
      $response = array();
      $parameters = $request->json()->all();
      
      $rules =  array(
            'name'    => 'required'
        );
        
        $messages = array(
            'name.required' => 'view name is required.',
            'updated_by.required' => 'user name is required.'
        );
      
      $validator = \Validator::make(array('name' => $parameters['name']), $rules, $messages);

      if(!$validator->fails()) {
            
            $createdView = UserViews::create(array('name'=>$parameters['name'], 'created_by'=>$parameters['created_by'], 'updated_by'=>$parameters['updated_by']));

            if(!empty($createdView->id) && !empty($parameters['views'])) {

               foreach($parameters['views'] as $k =>$v) {
                  $viewDetails = array();
                  $viewDetails['view_id'] = $createdView->id;
                  $viewDetails['service_name'] = $v;                  
                  $details = UserViewDetails::create($viewDetails);
                }
            }
            return return response()->json(createdView);
         } else {
            $errors = $validator->errors();
            return response()->json($errors->all());
         }
      
   }

Update record into Mysql Database Using Lumen and Eloquent

We will create new POST type method saveUserView() into UserViewsController.php file.This method will update record into table to corresponding view id.You need to send data into json format from client side.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
    * Method to save user View
    *
    * @author parvez.alam
    */
   public function saveUserView(Request $request) {
      $response = array();
      $parameters = $request->json()->all();
      
      $rules =  array(
            'name'    => 'required'
        );
        
        $messages = array(
            'name.required' => 'view name is required.'
        );
      //return $parameters;
      $validator = \Validator::make(array('name' => $parameters['name']), $rules, $messages);

      if(!$validator->fails()) {
            //return Helper::jsonpSuccess($parameters);
            $view = UserViews::find($parameters['id']);
            $view->name = $parameters['name'];
            $view->updated_by = $parameters['updated_by'];

            $saveView = $view->save();
            
            if(!empty($parameters['id']) && $saveView) {
                
               foreach($parameters['views'] as $k =>$v) {
                  
                  if($v['id'] > 0) {
                     if($v['status'] < 0) {
                        $viewDetails = UserViewDetails::find($v['id']);

                        $details = $viewDetails->delete();
                     }
                     //return Helper::jsonpSuccess($details); 
                  } else {
                     $viewDetails = array();
                     $viewDetails['view_id'] = $parameters['id'];
                     $viewDetails['service_name'] = $v['name'];
                     $viewDetails['updated_by'] = $parameters['updated_by'];                
                     $details = UserViewDetails::create($viewDetails);
                  }
                }
            }
            return response()->json($saveView);
         } else {
            $errors = $validator->errors();
            return response()->json($errors->all());
         }
      
   }

Delete record from Mysql Table Using Lumen and Eloquent

We will create Delete type request and new method deleteUserView() into UserViewsController.php file.This method will take view id as parameter and delete records from both tables.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
    * Method to delete user View
    *
    * @author parvez.alam
    */
   public function deleteUserView($id) {
      $response = array();

      if(!empty($id)) {
            $view = UserViews::find($id);
            $response = $view->UserViewDetails()->delete();
            $response = $view->delete();

            return response()->json($response);
         } else {
            
            return response()->json('Id is not defined!');
         }
      
   }

Conclusion

I have create basic crud functionality of listing records table using Mysql,lumen and Eloquent ORM.You can add records and edit existing records into mysql database using rest webservice. You can also delete record from database table using ORM. These are basic Rest api for any front-end application which want to add,edit and delete records.You can integrate these rest call to any web application which are communicating to server using APIs.