问一下大家,laravel怎么在api接口输出的时候多包一层data?谢谢~

大家好!我现在输出的json格式是这样子的

{
        "total": 0,
        "pages": 0,
        "size": 0,
        "page": 1,
        "data": [
            {
                "id": "6",
                "created_at": "2021-09-04T17:34:05.000Z",
                "updated_at": "2022-02-25T09:48:41.000Z",
                "title": "启动界面视频广告",
                "icon": "assets/splash_ad.mp4",
                "uri": "/courses",
                "style": 10,
                "position": 10,
                "sort": 1000,
                "user_id": "1417780635407372289"
            },
            {
                "id": "5",
                "created_at": "2021-09-04T17:34:05.000Z",
                "updated_at": "2022-02-25T09:48:41.000Z",
                "title": "启动界面图片广告",
                "icon": "assets/splash_ad.png",
                "uri": "/books",
                "style": 0,
                "position": 10,
                "sort": 900,
                "user_id": "1417780635407372289"
            }
        ]
    }

代码如下,
控制器代码

    public function getBraceCaseCommentList($case_id)

    {
        $brace_case_comments = BraceCaseComment::where('case_id', $case_id)->orderBy('id', 'desc')->paginate(10);
        return ResourcesBraceCaseComment::collection($brace_case_comments);
    }

资源包裹代码

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PreHomeDoing extends JsonResource
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $data = parent::toArray($request);
        $data['image_url'] = optional($this->pre_home_doing_image)->url;
        $data['nickname'] = $this->yt_user->nickname;
        $data['headimgurl'] = $this->yt_user->headimgurl;
         return $data;
    }
}

但是公司和前端都要求加一层data,
json格式如下:

{
    "data": {
        "total": 0,
        "pages": 0,
        "size": 0,
        "page": 1,
        "data": [
            {
                "id": "6",
                "created_at": "2021-09-04T17:34:05.000Z",
                "updated_at": "2022-02-25T09:48:41.000Z",
                "title": "启动界面视频广告",
                "icon": "assets/splash_ad.mp4",
                "uri": "/courses",
                "style": 10,
                "position": 10,
                "sort": 1000,
                "user_id": "1417780635407372289"
            },
            {
                "id": "5",
                "created_at": "2021-09-04T17:34:05.000Z",
                "updated_at": "2022-02-25T09:48:41.000Z",
                "title": "启动界面图片广告",
                "icon": "assets/splash_ad.png",
                "uri": "/books",
                "style": 0,
                "position": 10,
                "sort": 900,
                "user_id": "1417780635407372289"
            }
        ]
    },
    "status": 0
}

请问一下大家,外边的这层data,怎么加上去的?谢谢祝大家新年快乐

什么时候开始都不晚,学到老
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 23

我是这样子写的。

//失败返回
    public function error($code=422,$data="",$msg="fail"){
        $result = [
            "code"=>$code,
            "message"=>$msg,
            "data"=>$data
        ];
        return response()->json($result,200);
    }

想要什么格式都可以自定义的。

分页的可以是这样

public function success_list($data,$msg="成功" ,$total=0,$page=1,$limit=15){
        $result = [
            "code"=>200,
            "message"=>$msg,
            "data"=>[
                'total'=>$total,
                'page'=>$page,
                'limit'=>$limit,
                'data'=>$data
            ]
        ];
        return response()->json($result,200);
    }
1年前 评论
芝麻开门 (楼主) 1年前
我爱大可乐 (作者) 1年前
porygonCN

file

1年前 评论
芝麻开门 (楼主) 1年前
porygonCN (作者) 1年前

这样:

return response()->json();

public function json($data = [], $status = 200, array $headers = [], $options = 0);
1年前 评论
芝麻开门 (楼主) 1年前

自己封装统一返回格式就好了。

我是封装个类似 BaseController,里面封装统一的接口返回相应

protected function apiResponse($responseData = null, $message = '', $code = 1, $statusCode = 200)
{
    return response()
       ->json(returnData($code, $message, $responseData, $statusCode))
        ->setStatusCode($statusCode);
}

returnData是helper封装的方法

if (! function_exists('returnData')) {
    function returnData($code = 0, $msg = '', $data = null, $statusCode = 200)
    {
       // ...
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }
}

最终控制器继承 BaseController就可以直接使用了

$list = [];
return $this->apiResponse($list, '请求列表成功');
1年前 评论
芝麻开门 (楼主) 1年前

file

1年前 评论
芝麻开门 (楼主) 1年前
芝麻开门 (楼主) 1年前
芝麻开门 (楼主) 1年前
public  function  toArray($request)  { 
    $data = parent::toArray($request);
    $data['image_url'] = optional($this->pre_home_doing_image)->url;
    $data['nickname'] = $this->yt_user->nickname;
    $data['headimgurl'] = $this->yt_user->headimgurl;
    return  ['data'=>$data];  
}

是这样吗?

1年前 评论

这什么奇葩需求,搞得有点像 GraphQL

1年前 评论
$list = $logs->orderBy('complete_time', 'desc')->paginate(20);
 $temp = $list->map(function ($v) {
            return new MaterialChangeLog($v);
   });
   $arr = $list->toArray();
   $arr['data'] = $temp;
$json=[
        'status'=>0,
        'msg' =>$msg,
        'data' =>$arr,
    ];
   return response()->json($json)->setEncodingOptions(JSON_UNESCAPED_UNICODE);

试试上面的代码。

1年前 评论

BaseResourceCollection.php

<?php

namespace App\Ace\AdvanceSearch\Resource;

use App\Traits\Response\APIResponseCode;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\AbstractPaginator;

class BaseResourceCollection extends ResourceCollection
{
    use CommonResourceTrait;

    /**
     * The additional data that should be added to the top-level resource array.
     *
     * @var array
     */
    public $with = [
        'code' => APIResponseCode::SUCCESS,
        'message' => 'success',
    ];

    /**
     * Create an HTTP response that represents the object.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function toResponse($request): JsonResponse
    {
        $response = $this->resource instanceof AbstractPaginator
            ? (new CustomPaginatedResourceResponse($this))->toResponse($request)
            : parent::toResponse($request);

        return $response->setEncodingOptions(JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
    }
}

CustomPaginatedResourceResponse.php

<?php

namespace App\Ace\AdvanceSearch\Resource;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\PaginatedResourceResponse;
use JetBrains\PhpStorm\ArrayShape;

class CustomPaginatedResourceResponse extends PaginatedResourceResponse
{
    /**
     * Add the pagination information to the response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    #[ArrayShape(['meta' => 'array'])]
    protected function paginationInformation($request): array
    {
        $paginator = $this->resource->resource;

        $currentPage = (int) $paginator->currentPage();

        $pageMeta = [
            'page' => $currentPage,
            'page_size' => (int) $paginator->perPage(),
            'has_more' => $paginator->hasMorePages(),
        ];

        if (is_a($paginator, LengthAwarePaginator::class)) {
            $pageMeta['total'] = (int) $paginator->total();
        }

        return [
            'meta' => $pageMeta,
        ];
    }
}

在资源那个文章内有提到data 包裹方式,我们这边的实现可参考

1年前 评论

自定义一个 respondUtil 不就好了..

1年前 评论

以下代码可以实现您的需求:

public function toArray($request)
{
    $data = parent::toArray($request);
    $data['image_url'] = optional($this->pre_home_doing_image)->url;
    $data['nickname'] = $this->yt_user->nickname;
    $data['headimgurl'] = $this->yt_user->headimgurl;
    $res['data'] = $data;
    return $res;
}

如果上面的代码不行,可以用下面的:

public function getBraceCaseCommentList($case_id)
{
    $brace_case_comments = BraceCaseComment::where('case_id', $case_id)->orderBy('id', 'desc')->paginate(10);
    $res['data'] = ResourcesBraceCaseComment::collection($brace_case_comments);
    return $res;
}
1年前 评论

用这个方法解决了,感谢大家

public function usersInfo($id)
{
    $user = User::where('id', $id)->first();
    return $this->respondWithJsonData($user);
}


protected function respondWithJsonData($user)
{
    return response()->json([
        'data' => $user,
    ]);
}
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!