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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
~ mkdir example-laravel-api
~ cd example-laravel-api
~ mkdir example-laravel-api ~ cd example-laravel-api
~ 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
~ wget https://github.com/laravel/laravel/archive/develop.zip
~ unzip develop
~ sudo mv laravel-develop/* .
~ sudo rm -rf *develop*
~ composer install
~ wget https://github.com/laravel/laravel/archive/develop.zip ~ unzip develop ~ sudo mv laravel-develop/* . ~ sudo rm -rf *develop* ~ composer install
~ 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”.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
~ php artisan migrate:make create_blog_posts
~ php artisan migrate:make create_blog_posts
~ php artisan migrate:make create_blog_posts

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app/database/migrations/year_month_day_time_create_blog_posts.php
app/database/migrations/year_month_day_time_create_blog_posts.php
app/database/migrations/year_month_day_time_create_blog_posts.php

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?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');
}
}
<?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'); } }
<?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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
app/config/database.php
app/config/database.php
app/config/database.php

and replace this line:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
'default' => ‘mysql’,
'default' => ‘mysql’,
'default' => ‘mysql’,

with that one:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
'default' => 'sqlite',
'default' => 'sqlite',
'default' => 'sqlite',

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artisan migrate
php artisan migrate
php artisan migrate

The output should be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> Migration table created successfully.
> Migrated: 2013_04_12_130101_create_blog_posts
> Migration table created successfully. > Migrated: 2013_04_12_130101_create_blog_posts
> 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

Goodies von Mayflower

Keine Sorge – Hilfe ist nah! Melde Dich unverbindlich bei uns und wir schauen uns gemeinsam an, ob und wie wir Dich unterstützen können.


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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
// app/models/BlogPosts.php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class BlogPosts extends Eloquent
{
protected $table = 'blog_posts';
}
<?php // app/models/BlogPosts.php use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; class BlogPosts extends Eloquent { protected $table = 'blog_posts'; }
<?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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Route::get('/blog_posts', function ()
{
return BlogPosts::all();
});
Route::get('/blog_posts', function () { return BlogPosts::all(); });
Route::get('/blog_posts', function ()
{
    return BlogPosts::all();
});

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
~ cd public
~ php -S localhost:8080
~ cd public ~ php -S localhost:8080
~ 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[]
[]
[]

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd ..
cd ..
cd ..

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

And add our seeds class after the DatabaseSeeder class:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class BlogPostsSeeder extends Seeder {
public function run()
{
DB::table('blog_posts')->delete();
BlogPosts::create(array(
'author' => 'Steven Klar',
'text' => 'Some blog text'
));
}
}
class BlogPostsSeeder extends Seeder { public function run() { DB::table('blog_posts')->delete(); BlogPosts::create(array( 'author' => 'Steven Klar', 'text' => 'Some blog text' )); } }
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// find:
// $this->call('UserTableSeeder');
// replace with:
$this->call('BlogPostsSeeder');
// find: // $this->call('UserTableSeeder'); // replace with: $this->call('BlogPostsSeeder');
// find:

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

// replace with:

$this->call('BlogPostsSeeder');

Back to commandline we let artisan seed our database:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
php artsian db:seed
php artsian db:seed
php artsian db:seed

Outputs > Database seeded!

Final result

Lets start our server again and see our result.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
~ cd public
~ php -S localhost:8080
~ cd public ~ php -S localhost:8080
~ cd public
~ php -S localhost:8080

We should get our blog post as JSON string:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[{"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"}]
[{"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"}]
[{"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/

Goodies von Mayflower

Keine Sorge – Hilfe ist nah! Melde Dich unverbindlich bei uns und wir schauen uns gemeinsam an, ob und wie wir Dich unterstützen können.

Webinar

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.