Create REST API Example Using Lumen Micro Framework by Laravel – Part II

In first part of lumen rest tutorial, I have covered configuration of lumen framework. We have also learned how to connect with lumen with MySQL.

Created migration script using PHP artisan command and migrated table into the database, Now We will gone through the next part of this lumen rest tutorial.

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.

How to define Model into Lumen/laravel 5

<?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 to define columns name which will use to insert/edit records and will send data from the server-side.create_on and updated_on column value will automatically insert using the current server time, you don’t need to send those col value to the 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.

<?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,

//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 written single-line comment on each route which are describing the rest apis what they will do.

You can also check other recommended tutorials of Lumen/Laravel,

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

<?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.

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.

/**
    * 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.

/**
    * 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 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.

/**
    * 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.

/**
    * 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.

You can download source code from below link.

Leave a Reply

Your email address will not be published. Required fields are marked *