laravel:返回统一格式的json

一,参考文档

https://learnku.com/docs/laravel/10.x/responses/14850

二,php代码

1,App\extend\result\Result.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
/*
   统一格式的返回json数据
*/
namespace App\extend\result;
 
class Result {
    //success:code值为0,data:数据
    static public function Success($data) {
        $rs = [
            'code'=>0,
            'msg'=>"",
            'data'=>$data,
        ];
        return response()->json($rs);
    }
    //ErrorCode:需要code/msg参数
    static public function ErrorCode($code,$msg) {
        $rs = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>"",
        ];
        return response()->json($rs);
    }
    //error,传入定义的数组常量
    static public function Error($arr) {
        $rs = [
            'code'=>$arr['code'],
            'msg'=>$arr['msg'],
            'data'=>"",
        ];
        return response()->json($rs);
    }
}

2,controller中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
 
use App\extend\result\Result;
 
class NewsController extends Controller
{
    //使用统一返回的数据格式
    public function res(Request $request) {
 
        //判断是否存在name参数,如果存在
        if ($request->has('name')) {
           $data = [
            'name'=>$request->name,
            'age'=>'24',
          ];
 
           return Result::Success($data);
        } else {   //参数不存在时返回错误
            return Result::ErrorCode(10024,'缺少name参数');
        }
    }

三,测试效果:

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/17/laravel-fan-hui-tong-yi-ge-shi-de-json/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

四,查看laravel框架的版本:

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0
posted @ 2023-10-19 08:47  刘宏缔的架构森林  阅读(149)  评论(0编辑  收藏  举报