LoginSignup
2
8

More than 3 years have passed since last update.

laravelを使用したjsonを返すAPIの作り方

Last updated at Posted at 2019-07-15

Laravelのリソースクラスは、モデルやモデルコレクションを記述しやすく簡単に、JSONへと変換してくれます。

↑公式から引用

モデル作成

php artisan make:model UserSample

モデル記述

  • $fillableに指定したカラムのみ、create()やfill()、update()で値が代入されます。

  • モデルから変換する配列やJSONに、パスワードのような属性を含めたくない場合があります。それにはモデルの$hiddenプロパティに定義を追加してください。

/api/app/UserSample.php
namespace App;

use \App\UserSample;
use Illuminate\Database\Eloquent\Model;


class UserSample extends Model
{

    protected $table = 'UserSample';
//    上記コードでテーブル指定
    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

}

## コントローラー作成

php artisan make:resource UserSampleResource

コントローラー記述

/api/app/Http/Resources/UserSampleResource.php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserSample extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

route記述

/api/routes/api.php
<?php

use App\UserSample;
use Illuminate\Http\Request;
use App\Http\Resources\UserSampleResource;

Route::get('/user', function () {
    return new UserSampleResource(UserSample::all());
});

マイグレーション作成

php artisan make:migration UserSample

マイグレーション記述

/api/database/migrations/2019_07_15_042644_UserSample.php
<?php

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

class UserSample extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('UserSample', function (Blueprint $table) {
            $table->increments('id')->index();
            $table->string('name')->nullable();
            $table->string('email')->nullable();
            $table->string('password')->nullable();;
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

マイグレーション実行

php artisan migrate

実行する

ローカルにサーバーを立てる

php artisan serve

下記をGETする
http://localhost:8000/api/userSample

下記のようにjson形式でデータが返ってくるAPIの完成

{"data":[]}

次回はuserを作成するAPI開発について書く。

サンプルコード
https://github.com/taichi0514/laravel_sample_api-

2
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
2
8