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

举报
lxw1844912514 发表于 2022/03/27 01:21:43 2022/03/27
【摘要】 一般返回数据格式 return response()->json(['status' => 'success','code' => 200,'message' => '关注成功']); return response()->json(['status' => 'fail','code...

一般返回数据格式


    
  1. return response()->json(['status' => 'success','code' => 200,'message' => '关注成功']);
  2. return response()->json(['status' => 'fail','code' => 500,'error' => '关注失败',]);

基类控制器


    
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Foundation\Bus\DispatchesJobs;
  4. use Illuminate\Routing\Controller as BaseController;
  5. use Illuminate\Foundation\Validation\ValidatesRequests;
  6. use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
  7. class Controller extends BaseController
  8. {
  9. use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
  10. public function success($data = [])
  11. {
  12. return response()->json([
  13. 'status' => true,
  14. 'code' => 200,
  15. 'message' => config('errorcode.code')[200],
  16. 'data' => $data,
  17. ]);
  18. }
  19. public function fail($code, $data = [])
  20. {
  21. return response()->json([
  22. 'status' => false,
  23. 'code' => $code,
  24. 'message' => config('errorcode.code')[(int) $code],
  25. 'data' => $data,
  26. ]);

 


errorcode文件


    
  1. <?php
  2. return [
  3. /*
  4. |--------------------------------------------------------------------------
  5. | customized http code
  6. |--------------------------------------------------------------------------
  7. |
  8. | The first number is error type, the second and third number is
  9. | product type, and it is a specific error code from fourth to
  10. | sixth.But the success is different.
  11. |
  12. */
  13. 'code' => [
  14. 200 => '成功',
  15. 200001 => '缺少必要的参数',
  16. //文章
  17. 503001 => '上传文件的格式不正确',
  18. 503002 => '同步成功-记录保存失败',
  19. 503003 => '权限错误',
  20. 503004 => '文章保存失败',
  21. 403017 => '临近定时时间不能取消发送任务',
  22. 403018 => '临近定时时间不能修改发送任务',
  23. 403019 => '超过发送时间不能发送',
  24. 403020 => '缺少发表记录ID参数',
  25. //SMS
  26. 416001 => '添加成功,审核中,请耐心等待',
  27. 416002 => '签名添加失败',
  28. ],
  29. ];

  

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

返回引用


    
  1. return $this->fail(503003);
  2. return $this->Success();

  

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

文章来源: blog.csdn.net,作者:lxw1844912514,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/lxw1844912514/article/details/100028520

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。