Simple example with Laravel 4

Avatar von Steven Klar

Laravel is a clean and easy to use PHP web development framework which has ruby on rails as model and architecture concept.

We will create a short example to show how easy it is to receive json data from a Laravel 4 application to use it later in any random javascript application.

Preconditions

We need the following installations to accomplish this example:

  1. composer
  2. sqlite
  3. php 5.4

Setup

First we create our initial Laravel 4 setup:

~ mkdir example-laravel-api
~ cd example-laravel-api

We use composer for easy installing our Laravel package and its dependencies.
So lets download the last develop build from github and start the installation via composer.

~ wget https://github.com/laravel/laravel/archive/develop.zip
~ unzip develop
~ sudo mv laravel-develop/* .
~ sudo rm -rf *develop*
~ composer install

Our general application structure is there! :-)

Database Migration

Lets receive our blog posts as JSON when doing „/blog-posts“ GET-request.
So we can call that API later by our frontend javascript application and show our blog posts. :-)

To accomplish that we use the Laravel CLI-tool “artisan”.

~ php artisan migrate:make create_blog_posts

Artisan creates a new migration file for us which can be found here:

app/database/migrations/year_month_day_time_create_blog_posts.php

Lets open that file and write some migration which could be like this:

<?php

use Illuminate\Database\Migrations\Migration;

class CreateBlogPosts extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blog_posts', function($table)
        {
            $table->increments('id');
            $table->string('author');
            $table->string('text');
            $table->date('updated_at');
            $table->date('created_at');
        });
    }

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

}

Lets keep it simple for this example. We defined our primary key “id”, “author” for our name and “text” as our blog post content.

Database Configuration

Before we can use our migration we define our database params in

app/config/database.php

and replace this line:

'default' => ‘mysql’,

with that one:

'default' => 'sqlite',

Because we don’t need mysql for this example.
After that we start our migration with artisan.

php artisan migrate

The output should be:

> Migration table created successfully.
> Migrated: 2013_04_12_130101_create_blog_posts

We have our ‘blog_posts’ database table and use the Laravel native Eloquent ORM to create a model.

Active Record Model

Lets make use of the native Active Record „Eloquent“ model.
Create new file with following content:

<?php

// app/models/BlogPosts.php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class BlogPosts extends Eloquent
{
    protected $table = 'blog_posts';
}

Fine. How do we return these blog posts? Ah, we said something like request ‘/blog_posts’. Okay then, lets listen to that URI!

The simple router

Open > application/routes.php and add the following lines:

Route::get('/blog_posts', function ()
{
    return BlogPosts::all();
});

Lets start our PHP 5.4 server and to see what we get.

~ cd public
~ php -S localhost:8080

Please use another port if 8080 is already in use. ;-)
Browsing „http://localhost:8080/blog_posts“ should return something like this:

[]

Ah, it’s an empty JSON string!
That’s because Laravel recognize that we pass an eloquent model as response and expects to return JSON. Neat isn’t it?

Seeds in Laravel

So we need example blog posts. In Laravel we use seeds for that.

cd ..

Open the following database seeder file
> app/database/seeds/DatabaseSeeder.php

And add our seeds class after the DatabaseSeeder class:

class BlogPostsSeeder extends Seeder {

    public function run()
    {
        DB::table('blog_posts')->delete();

        BlogPosts::create(array(
            'author' => 'Steven Klar',
            'text' => 'Some blog text'
        ));
    }

}

Dont forget to add this class in that DatabaseSeeder – so we replace that:

// find:

// $this->call('UserTableSeeder');

// replace with:

$this->call('BlogPostsSeeder');

Back to commandline we let artisan seed our database:

php artsian db:seed

Outputs > Database seeded!

Final result

Lets start our server again and see our result.

~ cd public
~ php -S localhost:8080

We should get our blog post as JSON string:

[{"id":"1","author":"Steven Klar","text":"Some blog text","updated_at":"2013-04-12 13:30:31","created_at":"2013-04-12 13:30:31"}]

We’ve done it!

Resumé

That was a very quick tour how easy it is in Laravel to write an API like that.
Maybe in future we will get more into it.

Laravel 4 already has an awesome documentation.
So if you want more: http://four.laravel.com/

Avatar von Steven Klar

Kommentare

Eine Antwort zu „Simple example with Laravel 4“

  1. Nice Tutorial! Thanks

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


Für das Handling unseres Newsletters nutzen wir den Dienst HubSpot. Mehr Informationen, insbesondere auch zu Deinem Widerrufsrecht, kannst Du jederzeit unserer Datenschutzerklärung entnehmen.