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

发布时间:2021-08-11 09:56:36 作者:小新
来源:亿速云 阅读:104

这篇文章给大家分享的是有关Laravel如何自定义封装便捷返回Json数据格式的引用方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

一般返回数据格式

 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();

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

感谢各位的阅读!关于“Laravel如何自定义封装便捷返回Json数据格式的引用方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. json数据格式
  2. JSON数据格式详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel json

上一篇:PHP如何实现自动补全表单

下一篇:thinkPHP5.0框架环境变量配置的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》