Simple RESTfull API with Lumen – Laravel Microframework

Lumen is Laravel micro-framework that build for small web application and handle some micro-services. Nowadays people love to use Lumen for build fast API for their application.

Installing Lumen

if you have installed lumen installer using composer, you just need to type:

lumen new api

note

api : directory of project that you want to start build

or you can install lumen via composer create-project:

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

Check all your artisan command by type:

php artisan

Run lumen on your local server

php artisan serve

 

Screen Shot 2015-12-29 at 9.12.45 PM

For full documentation you can read here.

when the package downloaded, you can start modify .env file from rename .env.example file. Fill the database detail setting to connect with your database in your local machine.

APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomKey!!!
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
DB_CONNECTION=mysql
DB_HOST=DATABASE_HOST
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USER_NAME
DB_PASSWORD=DATABASE_PASSWORD

In the api/bootstrap/app.php uncommenting this following line:


Dotenv::load(__DIR__.'/../');
$app->withFacades();
$app->withEloquent();

 

Migration
this step is to create table in your database. In this example, there are article table that consist of 6 column.
id (auto increment), title varchar, content text, author varchar, update_at timestamp, and created_at timestamp.


php artisan make:migration --create=article create_article_table

 

it will create migration file under /database/migration . Edit xxx_create_article_table.php file

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->string('author');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('article');
    }
}
save and run :

php artisan migrate

you are now success to create article table in your database.

 

Model
create article model under App/Article.php
<?php namespace App;
 
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
     protected $fillable = ['title', 'content', 'author'];
    
}
?>

 

Controller

create article controller under app/Http/Controllers/ArticleController.php

<?php
namespace App\Http\Controllers;
use App\Book;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ArticleController extends Controller{
    public function index(){
        $Articles  = Article::all();
        return response()->json($Articles);
    }
 
    public function getArticle($id){
        $Article  = Article::find($id);
        return response()->json($Article);
    }
 
    public function createArticle(Request $request){
        $Article =Article::create($request->all());
        return response()->json($Article);
 
    }
 
    public function deleteArticle($id){
        $Article  =Article::find($id);
        $Article->delete();
        return response()->json('success');
    }
 
    public function updateArticle(Request $request,$id){
        $Article  =Article::find($id);
        $Article->title = $request->input('title');
        $Article->content = $request->input('content');
        $Article->author = $request->input('author');
        $Article->save();
        return response()->json($Article);
    }
 
}

Routing
Add your routing under app/Http/routes.php


$app->get('/', function () use ($app) {
return $app->welcome();
});
$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], function($app){
$app->get('article','ArticleController@index');
$app->get('article/{id}','ArticleController@getArticle');
$app->post('article','ArticleController@createArticle');
$app->put('article/{id}','ArticleController@updateArticle');
$app->delete('article/{id}','ArticleController@deleteArticle');
});

Run and test your api project on your local server using curl or i recomend you to use postman in chrome. Try in many method like get, post, put and delete.

example to get all article just type http://localhost/api/v1/article and set get method in your post man, it will return all article data in json format if you have already insert data before.

don’t forget to put id of article, if you want to request get 1 article, or update (put) and delete article ( single article )

if you want to add new article, simply you just need to fill the parameter title,content and author data that you want to add into database.

Installing Homestead in Mac OS X

Homestead is the simple way that YOU, code artisan want to build your project in your local computer and you want have setting of your local computer same as your production server. Here is Homestead come to you.

Homestead is a vagrant box that laravel special build for simplify developer work.

First of all you need to download and install Virtualbox and Vagrant before installing Homestead in your local computer.

Step 1 Installing composer

~> curl -sS https://getcomposer.org/installer | php
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: /Users/you/composer.phar
Use it: php composer.phar

once you have composer.phar downloaded, make it globally

~> sudo mv composer.phar /usr/local/bin/composer

add alias for composer in ~/.bash_profile

alias composer="php /usr/local/bin/composer.phar"

checking composer version

~> composer --version
Composer version 1.0-dev (b23a3cd36870ff0eefc161a4638d9fcf49d998ba)\
2014-11-21 17:59:11

Step 2 Adding ssh keys

check in your local computer if there is already ssh keys usually in ~/.ssh directory. If there is 2 files id_rsa and id_rsa.pub you don’t need to generate ssh keys again.

If you don’t see both files, you can generate it.

~> ssh-keygen -t rsa -C "your@email.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/you/.ssh/id_rsa):
Created directory '/Users/you/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

Step 3 Adding Homestead box

~> vagrant box add laravel/homestead
==> box: Loading metadata for box 'laravel/homestead'
    box: URL: https://vagrantcloud.com/laravel/homstead

it take a little while for download the box. If you already download, you can adding this box manually ( i assume that homestead.box file placed in your Download directory)

~> vagrant box add laravel/homestead ~/Download/homestead.box
==> box: Loading metadata for box 'laravel/homestead'
    box: URL: https://vagrantcloud.com/laravel/homstead

Step 4 Installing Homestead

~> composer global require "laravel/homestead=~2.0"
Changed current directory to /home/you/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing symfony/process (v2.5.7)
    Loading from cache

  - Installing symfony/console (v2.5.7)
    Loading from cache

  - Installing laravel/homestead (v2.0.7)
    Loading from cache

Writing lock file
Generating autoload files
  • updating you PATH in ~/.bash_profile
    export PATH="~/.composer/vendor/bin:vendor/bin:$PATH"

save and then reload using:

    ~> source ~/.bash_profile
  • Initializing Homestead
    ~> homestead init
    Creating Homestead.yaml file...
    Homestead.yaml file created at: /home/you/.homestead/Homestead.yaml

there is generate 3 files in ~/.homestead/ directory in your local computer. Go to ~/.homestead            directory and edit Homestead.yaml

---
ip:"192.168.10.10"
memory: 2048
cpus:1
authorize: ~/.ssh/id_rsa.pub
keys: - ~/.ssh/id_rsa
folders: - map: ~/Code
           to: /home/vagrant/Code
sites: - map: homestead.app
         to: /home/vagrant/Code/Laravel/public
databases: - homestead
variables: - key: APP_ENV
value: local

note:

  • folders : map-> here is your local directory that you want to share with VM ( usually it as /public_html directory). to -> here is in vm directory that linking your /public_html directory
  •  sites : map -> local domain to point your project. to-> project directory in vm that consist file of your project

in this example i use /Code directory as my public_html directory, you can create ~/Code directory before (do in your local computer) .

Step 5 Adding Local Domain

edit your /etc/hosts file to point your local domain and homestead IP

192.168.10.10 homestead.app

Step 6 Bringing Up Homestead

~>homestead up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'laravel/homestead'...
==> default: Matching MAC address for NAT networking...
==> default Checking if box 'laravel/homestead' is up to date...

you can log on to homestead using

~>homestead ssh
Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-11-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

Step 7 Installing Laravel

go to your public_html ( /Code ) directory in your local computer and then type:

~> composer global require "laravel/installer=~1.1"
Changed current directory to /Users/you/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing guzzlehttp/streams (2.1.0)
    Downloading: 100%

  - Installing guzzlehttp/guzzle (4.2.3)
    Downloading: 100%

  - Installing laravel/installer (v1.1.3)
    Downloading: 100%

Writing lock file
Generating autoload files

Step 8 Checking in Browser

go to your favorite browser and type your local domain  homestead.app for checking if Laravel success installed in our homestead box .

 

 

Modify length of word in the_excerpt function wordpress

Default length of words in the_excerpt function wordpress is 55 words . How to modify it ? when you think it is too long or you want more words to display it ?

– Adding this function in wp-includes/formatting.php

function string_limit_words($string, $word_limit)
{
$words = explode(‘ ‘, $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(‘ ‘, $words);
}

– add this line in templates page that you want to display the_excerpt

<?php $excerpt = get_the_excerpt(); echo string_limit_words($excerpt, n); ?>

: number of word that you want to display .

Installing Package in Sublime Text

Sublime text is one of my favorite IDE. After entering license a week ago , i will share here how to installing package in sublime text.

  1. select Preferences > Browse Package
  2. see the location of package that your sublime text installed
  3. download package control for sublime and put in package directory
  4. Restart sublime

For Installing package :

  1. press Ctrl ( command ) + Shift + P . type Package Controll : Install Package
  2. scroll down , choose what type of package that you want to install . ex : html5
  3. wait until installation process done.

this is some references package that might be needed http://www.sitepoint.com/10-essential-sublime-text-plugins-full-stack-developer/

Controlling lamp using DFRDuino and Twitter

Hai guyss ? missed me ? hahaha | well , iam back to share with you all . after completion my bachelor degree  in january 2013 and busy with my job now , i will share with you again 🙂 .  hmmm i will discuss something around my essay now . For fulfill my bachelor  degree , each student must create one software and i try to take microcontroller for my essay .

Controlling Lamp using DFRDuino Uno and Twitter

lets discuss it !

Hardware

iam using DFRDuino board , its same as arduino  . Only different producer , dont scare 🙂 and Relay for Hardware .

DFRDuino uno is hardware that designed with component consist USB to serial conventer port and some resistor and a microcontroller chip with kind of ATmega8U2 for main component. For DFRDuino board specification you can see in this link.

Relay Shield is an electrically operated switch . I use it for join with DFRDuino board and then connecting with lamp . See relay specification in here .

For hardware schema see picture 1.1

hardware schemapicture 1.1

For system schema see picture 1.2

rich_picturepicture 1.2

Software

python ( wxPython for GUI ) , Tweety Library, C in arduino and working with twitter API .

Here is my final stuff

Controlling lamp using twitter

in GUI , i create scheduling program if user want to create schedule for each lamp . Launch the program in desktop and its automate stream twitter time line in back ground for accept user request via mention .

enjoy 🙂

Error : \system\codeigniter\Common.php on line 130 & 136 in Code Igniter

Deprecated: Assigning the return value of new by reference is deprecated in C:\web\site\system\codeigniter\Common.php on line 130

Deprecated: Assigning the return value of new by reference is deprecated in C:\web\site\system\codeigniter\Common.php on line 136

if you got error like that , after uploading and try to load in your hosting . its may be complicated with PHP version

How to solve it ?

here is the step :

A. remove by condition set_magic_quotes_runtime

file: codeigniter/CodeIgniter.php (line: 60)

if(!phpversion()=='5.3.0')
set_magic_quotes_runtime(0); // Kill magic quotes 

B. remove all new object by reference, change ‘=&’ to ‘=’

from: $objects[$class] =& new $name();
became: $objects[$class] = new $name();

file: codeigniter/Common.php   (line: 130)
file: codeigniter/Common.php   (line: 136)
file: libraries/Loader.php   (line: 255)
file: database/DB.php       (line: 133)

$objects[$class] = new $name(); 

see: = new
C. since hyphen ‘-’ became special character in php 5.3, change this way:

file: config/config.php     (line: 153)

from:

$config['permitted_uri_chars'] = 'a-z ~%.:_\-'; 

to:

$config['permitted_uri_chars'] = '~%.:_\-'; 

file: libraries/URI.php     (line: 189)

from:

if ( ! preg_match("|^[".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", $str)) 

to:

if ( !
preg_match("|^[\w".preg_quote($this->config->item('permitted_uri_chars'))."]+$|i", $str)) 

wacth!:
! preg_match(”|^[\w

 Try to load your website again 🙂