LoginSignup
4
8

More than 5 years have passed since last update.

最少手順でLaravel APIを試す

Last updated at Posted at 2018-03-04

たぶん最少手順。

やりたいこと

  • とりあえずLaravelでJSON返すAPIを作ってみたい
  • 試したいだけなのでDBとか使わない

前提

  • PHP7.x導入
  • Composer導入
  • Laravelプロジェクト作成

以上は済んでる前提で。
本稿環境はPHP7.2, Laravel5.6。

手順

Controller作成

php artisan make:controller ApiTestController --resource

作られたController見るといろいろメソッドがあるがindex()だけ編集。
適当な配列返す機能を実装。

app/Http/Controllers/ApiTestController.php
public function index()
{
    $testData = [
        ["id" => "1", "title" => "foo"],
        ["id" => "2", "title" => "bar"],
        ["id" => "3", "title" => "baz"]
    ];
    return $testData;
}

Routes編集

末尾に以下を追記。

routes/web.php
// APIテスト
Route::resource('test', 'ApiTestController');

ビルドインサーバー起動

php artisan serve

動作確認

localhost:8000/test

スクリーンショット 2018-03-04 13.19.38.png

こんな感じでJSON出力を確認できたらOK。

参考

  • 『PHPフレームワーク Laravel入門』(掌田津耶乃, 秀和システム, 2017)
4
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
8