Laravel 5.6 - Pass additional parameters to API Resource?

前端 未结 6 994
天涯浪人
天涯浪人 2020-12-28 17:26

A Laravel API Resource can be either a single resource or a collection. In some cases, additional parameters are required to be passed to the resource/collection from the co

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 18:03

    You can pass the extra parameters in as part of the call to the API endpoint. You can then access the parameters with the $request object (for your example) in the UserResource.

    For example, if you call the endpoint from a client such a web browser, axios, etc. using something like:

    http://localhost:3000/api/users?apple=true
    

    this will make the parameter apple with a value of true available in the controller. Without any other action on your part it will then also be accessible in the toArray($request) of the UserResource. You can access it similar to:

    public function toArray($request) {
          $isApple = $request->apple;
    
            return [
                'id'     => (int) $this->id, 
                'name'   => $this->name,
                'fruit'  => $isApple ? 'apple' : 'banana',
            ];
        }
    

提交回复
热议问题