Tech memo

日々学んだ技術のびぼうろく

Lumen 5.3 と Vue.js 2.1 で簡易掲示板を作る 〜バックエンド編〜


完成目標

このような簡易掲示板を作る。 f:id:yjhm214:20170105214532p:plain

フロントエンド編はこちら。

www.yjhm214.com

スポンサーリンク

前提

Lumen はインストール済み www.yjhm214.com

  • Lumen 5.3.3
  • Vue.js 2.1.4

まずはAPI をつくる。

準備

ファサードと Eloquent ORM を使えるようにするため、 bootstarp/app.php

// $app->withFacades();

// $app->withEloquent();

の部分のコメントをはずしておく。

テーブルの作成

マイグレート機能を使用してテーブルを作成する。

まずはマイグレートファイルを作成する。

$ php artisan make:migration create_comments_table --create comments

database/migrations ディレクトリ以下に現在日時のマイグレートファイルが作成されるので、 下記のようにテーブル定義を作成する。

<?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('comment');
            $table->timestamps();
        });
    }

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

テーブル定義ができたらマイグレートを実行してテーブルを作成する。

$ php artisan migrate

テーブルができた。

mysql> desc comments;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   |     | NULL    |                |
| comment    | text             | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

モデルの作成

comments テーブルを扱うためのモデルを作成する。 ディレクトリはapp/Comment.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model 
{
    protected $fillable = ['name', 'comment'];
}

ルーティングの作成

routes/api.phpを作成し、ルーティングを定義する。

$app->get('api/comment', 'CommentController@getAll');
$app->post('api/comment', 'CommentController@post');

このルーティングを有効にするため、 ルーティングの読み込みをファイルを変更する。 bootstrap/app.php

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__.'/../routes/api.php';
});

コントローラの作成

コントローラをapp/Http/Controllers/CommentController.phpとして作成する。 簡略化のため、エラー処理やバリデーションは入れていない。

<?php namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use App\Comment;

class CommentController extends BaseController 
{
    /**
     * Get all comments as JSON
     *
     * @return Response
     */
    public function getAll()
    {
        return response()->json(Comment::get());
    }
    
    /**
     * Save a newly created resource in storage.
     *
     * @return Response
     */
    public function post(Request $request)
    {
        return response()->json(Comment::create($request->all()));
    }
}

これで API は完成。

スポンサーリンク

関連記事

www.yjhm214.com

www.yjhm214.com