Laravel自定义 封装便捷返回Json数据格式的引用方法

2025-05-29 0 39

一般返回数据格式

?

1

2

3
return response()->json(['status' => 'success','code' => 200,'message' => '关注成功']);

return response()->json(['status' => 'fail','code' => 500,'error' => '关注失败',]);

基类控制器

?

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

namespace App\\Http\\Controllers;

use Illuminate\\Foundation\\Bus\\DispatchesJobs;

use Illuminate\\Routing\\Controller as BaseController;

use Illuminate\\Foundation\\Validation\\ValidatesRequests;

use Illuminate\\Foundation\\Auth\\Access\\AuthorizesRequests;

class Controller extends BaseController

{

use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

public function success($data = [])

{

return response()->json([

'status' => true,

'code' => 200,

'message' => config('errorcode.code')[200],

'data' => $data,

]);

}

public function fail($code, $data = [])

{

return response()->json([

'status' => false,

'code' => $code,

'message' => config('errorcode.code')[(int) $code],

'data' => $data,

]);

}

}

errorcode文件

?

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

return [

/*

|--------------------------------------------------------------------------

| customized http code

|--------------------------------------------------------------------------

|

| The first number is error type, the second and third number is

| product type, and it is a specific error code from fourth to

| sixth.But the success is different.

|

*/

'code' => [

200 => '成功',

200001 => '缺少必要的参数',

//文章

503001 => '上传文件的格式不正确',

503002 => '同步成功-记录保存失败',

503003 => '权限错误',

503004 => '文章保存失败',

403017 => '临近定时时间不能取消发送任务',

403018 => '临近定时时间不能修改发送任务',

403019 => '超过发送时间不能发送',

403020 => '缺少发表记录ID参数',

//SMS

416001 => '添加成功,审核中,请耐心等待',

416002 => '签名添加失败',

],

];

可以对状态信息进行归类,如4–为用户端错误,5–位服务器端错误,2–为请求成功 。。。。。。。

返回引用

?

1

2

3

4
return $this->fail(503003);

return $this->Success();

Laravel自定义 封装便捷返回Json数据格式的引用方法

以上这篇Laravel自定义 封装便捷返回Json数据格式的引用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/qq_34827048/article/details/78486599

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Laravel自定义 封装便捷返回Json数据格式的引用方法 https://www.kuaiidc.com/92379.html

相关文章

发表评论
暂无评论