laravel result api风格封装公共响应(response)函数

在app/Http/Controllers/Controller.php中封装响应函数响应api请求。

<?php
namespace App\Http\Controllers;
public function index(){
    $data = Group::query()->where('pid',null)->with('son')->get(['id','pid','name','admin_name','phone','remark']);
    foreach ($data as $key => $value){
        $data[$key]['son'] = $value->son;
    }
    return $this->success($data);
}

修改app/Http/Controllers/Controller.php文件为一下内容

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Response;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    protected $statusCode=200;

    /**
     * @return int
     */
    public function getStatusCode(){
        return $this -> statusCode;
    }

    /**
     * @param $statusCode
     * @return mixed
     */
    public function setStatusCode($statusCode){
        $this -> statusCode = $statusCode;
        return $this;
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function success($data = []){
        return $this -> setStatusCode(200) -> responseSuccess($data);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function successMsg($msg = 'success'){
        return $this -> setStatusCode(200) -> responseSuccessMsg($msg);
    }

    /**
     * @param string $msg
     * @param string $msg_type  msg提示||alter警告||notify通知||box弹窗提示
     * @param string $level info普通||success成功||warning警告||error错误
     * @return mixed
     */
    public function warning($msg = 'warning',$msg_type = 'message',$level = 'info'){
        return $this -> setStatusCode(205) -> responseWarning($msg,$msg_type,$level);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function failed($msg = 'failed'){
        return $this -> setStatusCode(400) -> responseError($msg);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function notFound($msg = 'not found'){
        return $this -> setStatusCode(404) -> responseError($msg);
    }

    /**
     * @param $data
     * @return mixed
     */
    public function created($data){
        return $this -> setStatusCode(201) -> responseSuccess($data);
    }

    public function exists($msg = 'data already exists'){
        return $this -> setStatusCode(202) -> responseWarning($msg);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function badRequest($msg = 'Request Parameter Error!'){
        return $this -> setStatusCode(422) -> responseError($msg);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function unauthorized($msg = 'Unauthorized requests'){
        return $this -> setStatusCode(401) -> responseError($msg);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function forbidden($msg = 'Insufficient authority'){
        return $this -> setStatusCode(403) -> responseError($msg);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function methodNotAllowed($msg = 'This request is disabled'){
        return $this -> setStatusCode(405) -> responseError($msg);
    }

    /**
     * @param string $msg
     * @return mixed
     */
    public function serverError($msg = 'server error!'){
        return $this -> setStatusCode(500) -> responseError($msg);
    }

    /**
     * @param $msg
     * @return JsonResponse
     */
    protected function responseError($msg)
    {
        return $this -> response([
            'result' => 'FAILED',
            'status_code' => $this -> getStatusCode(),
            'msg' => $msg
        ])->setStatusCode($this -> getStatusCode());
    }

    /**
     * @param array $data
     * @return JsonResponse
     */
    protected function responseSuccess($data = []){
        return $this -> response([
            'result' => 'SUCCESS',
            'status_code' => $this -> getStatusCode(),
            'data' => $data
        ])->setStatusCode($this -> getStatusCode());
    }

    /**
     * @param $msg
     * @param $msg_type
     * @param $level
     * @return JsonResponse
     */
    public function responseWarning($msg,$msg_type,$level){
        return $this -> response([
            'result' => 'WARNING',
            'status_code' => $this -> getStatusCode(),
            'msg' => $msg,
            'msg_type' => $msg_type,
            'level' => $level
        ])->setStatusCode($this -> getStatusCode());
    }

    /**
     * @param $msg
     * @return JsonResponse
     */
    public function responseSuccessMsg($msg){
        return $this -> response([
            'result' => 'SUCCESS',
            'status_code' => $this -> getStatusCode(),
            'msg' => $msg
        ])->setStatusCode($this -> getStatusCode());
    }



    /**
     * @param $data
     * @return JsonResponse
     */
    public function response($data){
        return Response::json($data,$this -> getStatusCode());
    }

    //手动分页
    function paginate($data,$perPage,$current_page){
        $allItem = $perPage * 100;
        global $total;
        if($total > $allItem){
            $total = $allItem;
        }else{
            $total = count($data);
        }
        $item =array_slice($data,($current_page-1)*$perPage,$perPage);
        return new LengthAwarePaginator($item,$total,$perPage,$current_page,[
            'path'=> \Illuminate\Pagination\Paginator::resolveCurrentPath(),
            'pageName'=>'page'
        ]);
    }
}

使用方法示例(此处提供一个用户组的增删改查示例)

<?php

namespace App\Http\Controllers\Admin\Base;

use App\Http\Controllers\Controller;
use App\Models\Base\Group;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

class GroupController extends Controller
{
    public function index(){
        $data = Group::query()->where('pid',null)->with('son')->get(['id','pid','name','admin_name','phone','remark']);
        foreach ($data as $key => $value){
            $data[$key]['son'] = $value->son;
        }
        return $this->success($data);
    }

    public function store(Request $request){
        $param = $request->all();
        $create = Group::query()->create($param);
        return $create ? $this->successMsg() : $this->failed();
    }

    public function update(Request $request,$id){
        $param = $request->all();
        $group = Group::query()->find($id);
        $group->fill($param);
        return $group->save() ? $this->successMsg() : $this->failed();
    }

    public function show($id){
        $group = Group::query()->find($id);
        return $group ? $this->success($group) : $this->failed();
    }

    public function destroy($id){
        return Group::destroy($id) ? $this->successMsg() : $this->failed();
    }
}