Readouble

Laravel 5.8 Eloquent: APIリソース

イントロダクションIntroduction

API構築時、Eloquentモデルと、アプリケーションユーザーに対して実際に返信するJSONリスポンスとの間に、トランスレーション層を設置することが必要となります。Laravelのリソースクラスは、モデルやモデルコレクションを記述しやすく簡単に、JSONへと変換してくれます。When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

リソース生成Generating Resources

リソースクラスを生成するには、make:resource Artisanコマンドを使用します。リソースはデフォルトで、アプリケーションのapp/Http/Resourcesディレクトリに設置されます。リソースは、Illuminate\Http\Resources\Json\JsonResourceクラスを拡張します。To generate a resource class, you may use the make:resource Artisan command. By default, resources will be placed in the app/Http/Resources directory of your application. Resources extend the Illuminate\Http\Resources\Json\JsonResource class:

php artisan make:resource User

コレクションのリソースResource Collections

個別のモデルのリソースに加え、モデルのコレクションを変換し、返信するリソースを生成することも可能です。これにより、レスポンスにリンクと、指定したコレクションリソース全体を表す他のメタ情報を含めることができるようになります。In addition to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your response to include links and other meta information that is relevant to an entire collection of a given resource.

コレクションリソースを生成するには、リソース生成時に--collectionフラグを指定してください。もしくは、リソース名へCollectionを含め、Laravelへコレクションリソースを生成するように指示できます。コレクションリソースは、Illuminate\Http\Resources\Json\ResourceCollectionクラスを拡張します。To create a resource collection, you should use the --collection flag when creating the resource. Or, including the word Collection in the resource name will indicate to Laravel that it should create a collection resource. Collection resources extend the Illuminate\Http\Resources\Json\ResourceCollection class:

php artisan make:resource Users --collection

php artisan make:resource UserCollection

概略Concept Overview

lightbulb">Tip!! このセクションは、リソースとコレクションリソースについて、大雑把に概略を説明します。リソースで実現可能な機能とカスタマイズについて深く理解するため、このドキュメントの他の部分もお読みください。{tip} This is a high-level overview of resources and resource collections. You are highly encouraged to read the other sections of this documentation to gain a deeper understanding of the customization and power offered to you by resources.

リソースを書く場合に指定可能な全オプションを説明する前に、最初はLaravelでリソースがどのように使われるかという点を俯瞰し、確認しておきましょう。リソースクラスは、JSON構造へ変換する必要のある一つのモデルを表します。例として、シンプルなUserクラスを見てみましょう。Before diving into all of the options available to you when writing resources, let's first take a high-level look at how resources are used within Laravel. A resource class represents a single model that needs to be transformed into a JSON structure. For example, here is a simple User resource class:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * リソースを配列へ変換する
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

レスポンスを送り返す時に、JSONへ変換する必要のある属性の配列を返す、toArrayメソッドを全リソースクラスで定義します。$this変数を使用し、直接モデルのプロパティへアクセスできる点に注目です。これはリソースクラスが、変換するためにアクセスするモデルの、プロパティとメソッドを自動的に仲介するからです。リソースが定義できたら、ルートやコントローラから返します。Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when sending the response. Notice that we can access model properties directly from the $this variable. This is because a resource class will automatically proxy property and method access down to the underlying model for convenient access. Once the resource is defined, it may be returned from a route or controller:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

コレクションリソースResource Collections

ページ付けしたリソースやコレクションを返す場合は、ルートかコントローラの中で、リソースインスタンスを生成する時に、collectionメソッドを使用します。If you are returning a collection of resources or a paginated response, you may use the collection method when creating the resource instance in your route or controller:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all());
});

これにより返信するコレクションに付加する必要のあるメタデータが、追加されるわけではありません。コレクションリソースレスポンスをカスタマイズしたい場合は、そのコレクションを表すための専用リソースを生成してください。Note that this does not allow any addition of meta data that may need to be returned with the collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection:

php artisan make:resource UserCollection

コレクションリソースを生成すれば、レスポンスに含めたいメタデータを簡単に定義できます。Once the resource collection class has been generated, you may easily define any meta data that should be included with the response:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * コレクションリソースを配列へ変換
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}

定義したコレクションリソースは、ルートかコントローラから返してください。After defining your resource collection, it may be returned from a route or controller:

use App\User;
use App\Http\Resources\UserCollection;

Route::get('/users', function () {
    return new UserCollection(User::all());
});

コレクションキーの保持Preserving Collection Keys

ルートからリソースコレクションが返ってくる場合、Laravelは単純な数字順にするように、コレクションのキーをリセットします。しかしながら、リソースクラスへpreserveKeysプロパティを追加し、コレクションのキーを保持するように指定できます。When returning a resource collection from a route, Laravel resets the collection's keys so that they are in simple numerical order. However, you may add a preserveKeys property to your resource class indicating if collection keys should be preserved:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * リソースのコレクションのキーを保持する
     *
     * @var bool
     */
    public $preserveKeys = true;
}

preserveKeysプロパティがtrueにセットされると、コレクションのキーは保持されるようになります。When the preserveKeys property is set to true, collection keys will be preserved:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all()->keyBy->id);
});

背後のリソースクラスのカスタマイズCustomizing The Underlying Resource Class

リソースコレクションの$this->collectionは、リソースクラスコレクションの単数形で、各アイテムのマッピング結果を自動的に収集します。コレクションのクラス名から、末尾のCollection文字列を除いたものが、単数形のリソースクラス名と仮定します。Typically, the $this->collection property of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection's class name without the trailing Collection string.

たとえば、UserCollectionは、指定ユーザーインスタンスをUserリソースへマッピングしようとします。この動作をカスタマイズする場合は、リソースコレクションの$collectsプロパティをオーバーライドしてください。For example, UserCollection will attempt to map the given user instances into the User resource. To customize this behavior, you may override the $collects property of your resource collection:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * このリソースを収集するリソース
     *
     * @var string
     */
    public $collects = 'App\Http\Resources\Member';
}

リソース記述Writing Resources

lightbulb">Tip!! 概略をまだ読んでいないのなら、ドキュメントを読み進める前に目を通しておくことを強くおすすめします。{tip} If you have not read the concept overview[#concept-overview], you are highly encouraged to do so before proceeding with this documentation.

リソースの本質はシンプルです。特定のモデルを配列に変換する必要があるだけです。そのため、APIフレンドリーな配列としてユーザーへ送り返せるように、モデルの属性を変換するためのtoArrayメソッドをリソースは持っています。In essence, resources are simple. They only need to transform a given model into an array. So, each resource contains a toArray method which translates your model's attributes into an API friendly array that can be returned to your users:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * リソースを配列へ変換する
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

リソースを定義したら、ルートかコントローラから、直接返してください。Once a resource has been defined, it may be returned directly from a route or controller:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

リレーションRelationships

関連するリソースをレスポンスへ含めるには、toArrayメソッドから返す配列に追加します。以下の例では、Postリソースのcollectionメソッドを使用し、ユーザーのブログポストをリソースレスポンスへ追加しています。If you would like to include related resources in your response, you may add them to the array returned by your toArray method. In this example, we will use the Post resource's collection method to add the user's blog posts to the resource response:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->posts),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

lightbulb">Tip!! 既にロードされている場合のみ、リレーションを含めたい場合は、条件付きリレーションのドキュメントを参照してください。{tip} If you would like to include relationships only when they have already been loaded, check out the documentation on conditional relationships[#conditional-relationships].

コレクションのリソースResource Collections

リソースは一つのモデルを配列へ変換するのに対し、コレクションリソースはモデルのコレクションを配列へ変換します。モデルタイプそれぞれに対し、コレクションリソースを絶対に定義する必要があるわけではありません。すべてのリソースは、簡単に「アドホック」なコレクションリソースを生成するために、collectionメソッドを提供しています。While resources translate a single model into an array, resource collections translate a collection of models into an array. It is not absolutely necessary to define a resource collection class for each one of your model types since all resources provide a collection method to generate an "ad-hoc" resource collection on the fly:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all());
});

しかしながら、コレクションと一緒に返すメタデータをカスタマイズする必要がある場合は、コレクションリソースを定義する必要があります。However, if you need to customize the meta data returned with the collection, it will be necessary to define a resource collection:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * コレクションリソースを配列へ変換
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}

1モデルを扱うリソースと同様にコレクションリソースも、ルートやコントローラから直接返してください。Like singular resources, resource collections may be returned directly from routes or controllers:

use App\User;
use App\Http\Resources\UserCollection;

Route::get('/users', function () {
    return new UserCollection(User::all());
});

データラップData Wrapping

デフォルトではリソースレスポンスがJSONに変換されるとき、一番外側のリソースをdataキー下にラップします。たとえば、典型的なコレクションリソースのレスポンスは、次のようになるでしょう。By default, your outer-most resource is wrapped in a data key when the resource response is converted to JSON. So, for example, a typical resource collection response looks like the following:

{
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com",
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com",
        }
    ]
}

一番外部のリソースでラップしないようにしたい場合は、ベースのリソースクラスに対し、withoutWrappingメソッドを使用してください。通常、このメソッドはアプリケーションに対するリクエストごとにロードされる、AppServiceProviderか、もしくは他のサービスプロバイダから呼び出します。If you would like to disable the wrapping of the outer-most resource, you may use the withoutWrapping method on the base resource class. Typically, you should call this method from your AppServiceProvider or another service provider[/docs/{{version}}/providers] that is loaded on every request to your application:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Http\Resources\Json\Resource;

class AppServiceProvider extends ServiceProvider
{
    /**
     * コンテナ結合の登録
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * 全アプリケーションサービスの初期処理
     *
     * @return void
     */
    public function boot()
    {
        Resource::withoutWrapping();
    }
}

Note: note withoutWrappingメソッドは、最も外側のレスポンスだけに影響を与えます。コレクションリソースに皆さんが自分で追加したdataキーは、削除されません。{note} The withoutWrapping method only affects the outer-most response and will not remove data keys that you manually add to your own resource collections.

ネストしたリソースのラップWrapping Nested Resources

リソースのリレーションをどのようにラップするかは、完全に自由です。ネスト状態にかかわらず、dataキーの中に全コレクションリソースをラップしたい場合は、リソースそれぞれに対するコレクションリソースを定義し、dataキーにコレクションを含めて返す必要があります。You have total freedom to determine how your resource's relationships are wrapped. If you would like all resource collections to be wrapped in a data key, regardless of their nesting, you should define a resource collection class for each resource and return the collection within a data key.

それにより、最も外側のリソースが二重のdataキーでラップされてしまうのではないかと、疑うのは当然です。心配ありません。Laravelは決してリソースを間違って二重にラップしたりしません。変換するコレクションリソースのネストレベルについて、心配する必要はありません。You may be wondering if this will cause your outer-most resource to be wrapped in two data keys. Don't worry, Laravel will never let your resources be accidentally double-wrapped, so you don't have to be concerned about the nesting level of the resource collection you are transforming:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class CommentsCollection extends ResourceCollection
{
    /**
     * コレクションリソースを配列へ変換
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return ['data' => $this->collection];
    }
}

データラップとペジネーションData Wrapping And Pagination

リソースレスポンスの中から、ページ付けしたコレクションを返す場合、withoutWrappingメソッドが呼び出されていても、Laravelはリソースデータをdataキーでラップします。なぜなら、ページ付けしたレスポンスは、ペジネータの状態を含めたmetalinksキーを常に含めるからです。When returning paginated collections in a resource response, Laravel will wrap your resource data in a data key even if the withoutWrapping method has been called. This is because paginated responses always contain meta and links keys with information about the paginator's state:

{
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com",
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com",
        }
    ],
    "links":{
        "first": "http://example.com/pagination?page=1",
        "last": "http://example.com/pagination?page=1",
        "prev": null,
        "next": null
    },
    "meta":{
        "current_page": 1,
        "from": 1,
        "last_page": 1,
        "path": "http://example.com/pagination",
        "per_page": 15,
        "to": 10,
        "total": 10
    }
}

ペジネーションPagination

常にペジネータインスタンスをリソースのcollectionメソッドや、カスタムコレクションリソースへ渡せます。You may always pass a paginator instance to the collection method of a resource or to a custom resource collection:

use App\User;
use App\Http\Resources\UserCollection;

Route::get('/users', function () {
    return new UserCollection(User::paginate());
});

ページ付けしたレスポンスは常に、ペジネータの状態を含むmetalinksキーを持っています。Paginated responses always contain meta and links keys with information about the paginator's state:

{
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com",
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com",
        }
    ],
    "links":{
        "first": "http://example.com/pagination?page=1",
        "last": "http://example.com/pagination?page=1",
        "prev": null,
        "next": null
    },
    "meta":{
        "current_page": 1,
        "from": 1,
        "last_page": 1,
        "path": "http://example.com/pagination",
        "per_page": 15,
        "to": 10,
        "total": 10
    }
}

条件付き属性Conditional Attributes

条件が一致する場合のみ、リソースレスポンスへ属性を含めたいこともあります。たとえば、現在のユーザーが"administrator"の場合のみ、ある値を含めたいときです。こうした状況で役に立つ様々なヘルパメソッドをLaravelは提供しています。whenメソッドは条件により、リソースレスポンスへ属性を追加する場合に使用します。Sometimes you may wish to only include an attribute in a resource response if a given condition is met. For example, you may wish to only include a value if the current user is an "administrator". Laravel provides a variety of helper methods to assist you in this situation. The when method may be used to conditionally add an attribute to a resource response:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'secret' => $this->when(Auth::user()->isAdmin(), 'secret-value'),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

この例では、認証済みユーザーのisAdminメソッドがtrueを返す場合のみ、最終的なリソースレスポンスにsecretキーが返されます。メソッドがfalseの場合、クライアントへ送り返される前に、リソースレスポンスからsecretキーは完全に削除されます。whenメソッドにより、配列の構築時に条件文に頼らずに、リソースを記述的に定義できます。In this example, the secret key will only be returned in the final resource response if the authenticated user's isAdmin method returns true. If the method returns false, the secret key will be removed from the resource response entirely before it is sent back to the client. The when method allows you to expressively define your resources without resorting to conditional statements when building the array.

whenメソッドは、第2引数にクロージャを引き受け、指定した条件がtrueの場合のみ、結果の値を算出することもできます。The when method also accepts a Closure as its second argument, allowing you to calculate the resulting value only if the given condition is true:

'secret' => $this->when(Auth::user()->isAdmin(), function () {
    return 'secret-value';
}),

条件付き属性のマージMerging Conditional Attributes

リソースレスポンスへ同じ条件にもとづいて、多くの属性を含めたい場合もあります。この場合、指定した条件がtrueの場合のみ、レスポンスへ属性を組み入れるmergeWhenメソッドを使用します。Sometimes you may have several attributes that should only be included in the resource response based on the same condition. In this case, you may use the mergeWhen method to include the attributes in the response only when the given condition is true:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        $this->mergeWhen(Auth::user()->isAdmin(), [
            'first-secret' => 'value',
            'second-secret' => 'value',
        ]),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

このメソッドでも、指定した条件がfalseの場合、利用者へ送り返される前に、属性はリソースレスポンスから完全に取り除かれます。Again, if the given condition is false, these attributes will be removed from the resource response entirely before it is sent to the client.

Note: note mergeWhenメソッドは、文字列と数値のキーが混ざっている配列の中では、使用しないでください。さらに、順番に並んでいない数値キーの配列でも、使用しないでください。{note} The mergeWhen method should not be used within arrays that mix string and numeric keys. Furthermore, it should not be used within arrays with numeric keys that are not ordered sequentially.

条件付きリレーションConditional Relationships

条件によりロードする属性に付け加え、リレーションがモデルにロードされているかに基づいて、リソースレスポンスへリレーションを条件付きで含めることもできます。これにより、どのリレーションをモデルにロードさせるかをコントローラで決め、リソースが実際にロード済みの場合のみ、レスポンスへ含めることが簡単に実現できます。In addition to conditionally loading attributes, you may conditionally include relationships on your resource responses based on if the relationship has already been loaded on the model. This allows your controller to decide which relationships should be loaded on the model and your resource can easily include them only when they have actually been loaded.

究極的には、これによりリソースの中で、「N+1」クエリ問題を簡単に防ぐことができます。whenLoadedメソッドは、リレーションを条件付きでロードするために使用できます。不必要なリレーションのロードを防ぐために、このメソッドはリレーション自身の代わりに、リレーションの名前を引数に取ります。Ultimately, this makes it easier to avoid "N 1" query problems within your resources. The whenLoaded method may be used to conditionally load a relationship. In order to avoid unnecessarily loading relationships, this method accepts the name of the relationship instead of the relationship itself:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->whenLoaded('posts')),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

この例の場合、リレーションがロードされていない場合、postsキーは利用者へ送り返される前に、レスポンスから完全に取り除かれます。In this example, if the relationship has not been loaded, the posts key will be removed from the resource response entirely before it is sent to the client.

条件付きピボット情報Conditional Pivot Information

リソースレスポンスへ条件付きでリレーション情報を含める機能に付け加え、whenPivotLoadedメソッドを使用し、多対多リレーションの中間テーブルからのデータを含めることもできます。whenPivotLoadedメソッドは、第1引数に中間テーブルの名前を引き受けます。第2引数には、ピボット情報がそのモデルに対し利用可能な場合の返却値を定義するクロージャを指定します。In addition to conditionally including relationship information in your resource responses, you may conditionally include data from the intermediate tables of many-to-many relationships using the whenPivotLoaded method. The whenPivotLoaded method accepts the name of the pivot table as its first argument. The second argument should be a Closure that defines the value to be returned if the pivot information is available on the model:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'expires_at' => $this->whenPivotLoaded('role_user', function () {
            return $this->pivot->expires_at;
        }),
    ];
}

中間テーブルがpivot以外のアクセサにより使用されている場合は、whenPivotLoadedAsメソッドを使用してください。If your intermediate table is using an accessor other than pivot, you may use the whenPivotLoadedAs method:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'expires_at' => $this->whenPivotLoadedAs('subscription', 'role_user', function () {
            return $this->subscription->expires_at;
        }),
    ];
}

メタデータ追加Adding Meta Data

いくつかのJSON API規約では、リソースとコレクションリソースレスポンスで、追加のメタデータを要求しています。これらには、リソースへのlinkのような情報や、関連するリソース、リソース自体のメタデータなどがよく含まれます。リソースに関する追加のメタデータを返す必要がある場合は、toArrayメソッドに含めます。たとえば、コレクションリソースを変換する時に、link情報を含めるには次のようにします。Some JSON API standards require the addition of meta data to your resource and resource collections responses. This often includes things like links to the resource or related resources, or meta data about the resource itself. If you need to return additional meta data about a resource, include it in your toArray method. For example, you might include link information when transforming a resource collection:

/**
 * リソースを配列へ変換
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'data' => $this->collection,
        'links' => [
            'self' => 'link-value',
        ],
    ];
}

追加のメタデータをリソースから返す場合、ページ付けレスポンスへLaravelが自動的に付け加える、linksmetaキーを意図せずオーバーライドしてしまう心配はありません。追加のlinks定義は、ペジネータが提供するリンク情報にマージされます。When returning additional meta data from your resources, you never have to worry about accidentally overriding the links or meta keys that are automatically added by Laravel when returning paginated responses. Any additional links you define will be merged with the links provided by the paginator.

トップレベルメタデータTop Level Meta Data

一番外側のリソースが返される場合にのみ、特定のメタデータをリソースレスポンスへ含めたい場合があります。典型的な例は、レスポンス全体のメタ情報です。こうしたメタデータを定義するには、リソースクラスへwithメソッドを追加します。このメソッドには、一番外側のリソースを返す場合のみ、リソースレスポンスへ含めるメタデータの配列を返します。Sometimes you may wish to only include certain meta data with a resource response if the resource is the outer-most resource being returned. Typically, this includes meta information about the response as a whole. To define this meta data, add a with method to your resource class. This method should return an array of meta data to be included with the resource response only when the resource is the outer-most resource being rendered:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * コレクションリソースを配列へ変換
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }

    /**
     * リソース配列と共に返すべき、追加データの取得
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function with($request)
    {
        return [
            'meta' => [
                'key' => 'value',
            ],
        ];
    }
}

リソース構築時のメタデータ追加Adding Meta Data When Constructing Resources

ルートやコントローラの中で、リソースインスタンスを構築する時に、トップレベルのデータを追加することもできます。全リソースの中で利用可能なadditionalメソッドは、リソースレスポンスへ含めるべき追加データの配列を引数に取ります。You may also add top-level data when constructing resource instances in your route or controller. The additional method, which is available on all resources, accepts an array of data that should be added to the resource response:

return (new UserCollection(User::all()->load('roles')))
                ->additional(['meta' => [
                    'key' => 'value',
                ]]);

リソースレスポンスResource Responses

既に説明したように、リソースはルートかコントローラから直接返されます。As you have already read, resources may be returned directly from routes and controllers:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

しかし、利用者へ送信する前に、HTTPレスポンスをカスタマイズする必要が時々あります。リソースに対してresponseメソッドをチェーンしてください。このメソッドは、Illuminate\Http\Responseインスタンスを返しますので、レスポンスヘッダを完全にコントロールできます。However, sometimes you may need to customize the outgoing HTTP response before it is sent to the client. There are two ways to accomplish this. First, you may chain the response method onto the resource. This method will return an Illuminate\Http\Response instance, allowing you full control of the response's headers:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return (new UserResource(User::find(1)))
                ->response()
                ->header('X-Value', 'True');
});

もしくは、withResponseメソッドをレスポンス自身の中で定義することもできます。このメソッドはレスポンスの中で一番外側のリソースとして返す場合に呼び出されます。Alternatively, you may define a withResponse method within the resource itself. This method will be called when the resource is returned as the outer-most resource in a response:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
    /**
     * リソースを配列へ変換する
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
        ];
    }

    /**
     * リソースに対して送信するレスポンスのカスタマイズ
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\Response  $response
     * @return void
     */
    public function withResponse($request, $response)
    {
        $response->header('X-Value', 'True');
    }
}

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作