A custom encapsulation and convenient return of JSON data format reference in Laravel

JSON is a very common data exchange format. There are many ways to return JSON in Laravel, and the following is a common one.

return response()->json(['status' => 'success','code' => 200,'message' => 'you are allowed']);
or
return response()->json(['status' => 'fail','code' => 500,'error' => 'you are not allowed']);

We can use a simple way to encapsulate it, make it more easy to use。

First we add the following method to the base controller class.

<?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,
        ]);
    }
}

Define the error message configuration file.

return [

    /*
    |--------------------------------------------------------------------------
    | customized error code
    |--------------------------------------------------------------------------
    |
    | Error information can be categorized, such as 4-- client error, 5-- bit server error, 2-- request success...
    |
    */

    'code' => [
        200 => 'success',
        200001 => 'you are not allowed',
        200002 => 'a param is required',
        200003 => 'token expired',
    ],

];

Use it in actions.

return $this->fail(200002);

return $this->success();

Hope this post can help you.

RSS