![]() The whenLoaded method may be used to conditionally load a relationship. Ultimately, this makes it easier to avoid "N+1" query problems within your resources. ![]() 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. 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. Furthermore, it should not be used within arrays with numeric keys that are not ordered sequentially. ![]() The mergeWhen method should not be used within arrays that mix string and numeric keys. Resources extend the Illuminate\Http\Resources\Json\JsonResource class:Īgain, if the given condition is false, these attributes will be removed from the resource response before it is sent to the client. By default, resources will be placed in the app/Http/Resources directory of your application. To generate a resource class, you may use the make:resource Artisan command. Of course, you may always convert Eloquent models or collections to JSON using their toJson methods however, Eloquent resources provide more granular and robust control over the JSON serialization of your models and their relationships. However, if the foreign key on the Phone model is not userid, you may pass a custom key name as the second argument to the belongsTo method: Get the user that owns the phone. Eloquent's resource classes allow you to expressively and easily transform your models and model collections into JSON. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with id. For example, you may wish to display certain attributes for a subset of users and not others, or you may wish to always include certain relationships in the JSON representation of your models. 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.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |