当前位置:首页 > CMS教程 > 其它CMS > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-12-24 11:05:44 浏览: 评论:0 

一般返回数据格式

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

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

基类控制器

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

errorcode文件

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

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

返回引用

return $this->fail(503003);

return $this->Success();

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

Tags: Laravel自定义 Json

分享到: