欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

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

时间:2021-02-26 10:51:12|栏目:PHP代码|点击:

一般返回数据格式

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

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

基类控制器

<?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文件

<?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--为请求成功 。。。。。。。

返回引用

return $this->fail(503003);


return $this->Success();

上一篇:php基础知识:类与对象(3) 构造函数和析构函数

栏    目:PHP代码

下一篇:php强制文件下载而非在浏览器打开的自定义函数分享

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

本文地址:http://www.codeinn.net/misctech/70134.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有