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

  

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM