Lumen by Laravel first Tutorial

Lumen by Laravel first Tutorial

This a framework made from Taylor Otwell use the same core of Laravel but it’s designed to build service and little application where speed is on the first needs. Not all the component we use in Laravel are available in Lumen but it share only something with his father.

Personally i’ve never used so much component has it’s in Laravel so in most case Lumen can be a valid substitute, but if in the middle of a project you will need to upgrade to Laravel there isn’t problem, just copy and paste your code, it’s fully Laravel compatible.

Let’s begin with this very first tutorial for Lumen. We are going to write a simple REST API. This service can be used to serve an AngularJS page or can be given to an external client that need speed on the retrieve from your site. We will use Eloquent to write our query on the database, we will use the Migration utility available also on Lumen and the Routing feature.

Lumen confguration

Like said in the documentation you can install lumen via composer or the installer. With composer it will be

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

When the package is dowloaded we can start to modify the app.php for our needs, activating and configuring only the feature we need. In the app.php uncomment this line


Dotenv::load(__DIR__.'/../');

$app->withFacades();

$app->withEloquent();


Lumen support the .env configuration and we activated it uncommenting the line above. Rename the .env.example to .env and set the database property correctly for your environment.


APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomKey!!!

APP_LOCALE=en
APP_FALLBACK_LOCALE=en

DB_CONNECTION=mysql
DB_HOST=localhost:3306
DB_DATABASE=tutorial1
DB_USERNAME=tutorial1
DB_PASSWORD=tutorial1

CACHE_DRIVER=memcached
SESSION_DRIVER=memcached
QUEUE_DRIVER=database


The framework is now configured and we can start the service implementation.

Define a model

As we said at begin we will make a simple service to expose REST API to retrieve and insert articles in our database. First of all, we need a database table where store the article. From the command line

artisan make:migration create_articles_table --create=articles

We will make the article model very simple, just a title and a content. Most of the time the table will be already present in your main application but this time we are going to define it. In the created migration file :


<?php

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

class CreateArticlesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('articles', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('title');
			$table->string('content');
			$table->timestamps();
		});
	}

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

}


php artisan migrate

The command have created a migration table in the DB and the articles table too. The last thing in the model part is the class Article. In the app folder create a file Article.php


<?php namespace App;

 use Illuminate\Database\Eloquent\Model;
 

 class Article extends Model
 {
     
     protected $fillable = ['title', 'content'];
     
 }


The fillable properties is needed to assign properties to the object directly from the received Request.

The Controller

Now that the model is in place we have to implement the article controller. In the Http/Controllers folder create a new file ArticleController.php


<?php

namespace App\Http\Controllers;

use App\Article;
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 saveArticle(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->save();

        return response()->json($article);
    }

}


Using Eloquent as ORM the sintax of the various method are identical to a Laravel Controller. We implemented all the CRUD method for the Article class and returned objects in Json format. This simple API can be used for example in a AngularJS application.

Routing

The last part of the tutorial will be about routing. Route in Lumen work the same as Laravel. You can inject middleware and call controller method from it. One things to notice, but probably i’ve made something wrong on my side, to reference a controller class in the routes.php file i had to explicit the full path of the class. It looks like the autoload fails in some way.

The routes.php file will look so :


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

$app->get('/', function() use ($app) {
    return $app->welcome();
});



$app->get('api/article','App\Http\Controllers\[email protected]');

$app->get('api/article/{id}','App\Http\Controllers\[email protected]');

$app->post('api/article','App\Http\Controllers\[email protected]');

$app->put('api/article/{id}','App\Http\Controllers\[email protected]');

$app->delete('api/article/{id}','App\Http\Controllers\[email protected]');


Conclusion

Now all things are in the correct place and implemented in the right way. If you don’t want to write a complete application to test the api you can use POSTMAN, a good REST API client.

Lumen is young and probably it will grow faster but at the moment is a good solution if you need a fast service to implement and don’t want to take all the Laravel framework with it. The developer are the same of Laravel so we expect this little framework to become another industry standard in the PHP world.

Cheerss! Happy coding!

Adam Brown
Please follow and like us:

Leave a Comment