PHP code example of gzhpackages / laravel-json-api

1. Go to this page and download the library: Download gzhpackages/laravel-json-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gzhpackages / laravel-json-api example snippets


namespace App\Http\Controllers;

use GzhPackages\JsonApi\Traits\ApiHelper;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use ApiHelper;

    public function show()
    {
        // do something...
        return $this->content(['foo' => 'bar']);        
    }
    
    public function create()
    {
        // do something...
        return $this->created();
    }
}

function render($request, Exception $exception)
    {
        $rendered = parent::render($request, $exception);

        if (config('app.debug')) {
            return $rendered;
        }

        $status = $rendered->getStatusCode();
        $json = [
            'error' => array_merge(config('errors.server_error'), [
                'title' => 'SERVER_ERROR',
            ]),
        ];
        
        /* 捕获自定义错误 */
        if ($exception instanceOf \GzhPackages\JsonApi\Exceptions\BaseApiException) {
            $json = $exception->toArray();
            $status = $exception->getStatus();
        }
        
        /* 自定义内置的错误,统一返回json */
        if ($exception instanceOf \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            $json = [
                'error' => array_merge(config('errors.not_found'), [
                    'title' => 'NOT_FOUND',
                ]),
            ];           
            $status = 404;
        }

        if ($exception instanceOf \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
            $json = [
                'error' => array_merge(config('errors.method_not_allowed'), [
                    'title' => 'METHOD_NOT_ALLOWED',
                ]),
            ];    
            $status = 405;
        }

        return response()->json($json, $status);
    }

class NotFoundException extends BaseApiException
{
    protected $status = 404;
}

throw new NotFoundException('not_found_user', ['name' => 'xiaoming']);

$exception = new NotFoundException('not_found_user');
$exception->withMeta(['language' => 'en']);
throw $exception;

$app->register(GzhPackages\JsonApi\Providers\LaravelServiceProvider::class);
bash
php artisan make:api-exception NotFoundException