PHP code example of dantepiazza / laravel-api-response

1. Go to this page and download the library: Download dantepiazza/laravel-api-response 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/ */

    

dantepiazza / laravel-api-response example snippets


// 1. Helper function
api()->success()->response();

// 2. Facade
use DantePiazza\LaravelApiResponse\Facades\ApiResponse;
ApiResponse::success()->response();

// 3. Dependency injection (recommended for testability)
use DantePiazza\LaravelApiResponse\ApiResponse;

class UserController extends Controller
{
    public function __construct(private ApiResponse $api) {}

    public function index(): JsonResponse
    {
        return $this->api->success($users, 'Users retrieved')->response();
    }
}

// app/Http/Controllers/Controller.php
abstract class Controller
{
    public function __construct(protected ApiResponse $api) {}
}

api()->set(ApiResponse::STATUS_FAIL, 409, 'Already exists', $data);

// Status constants:
ApiResponse::STATUS_SUCCESS  // 'success'
ApiResponse::STATUS_FAIL     // 'fail'
ApiResponse::STATUS_ERROR    // 'error'

api()->success()
     ->data(['token' => $token, 'expires_in' => 3600])
     ->response();

api()->success()->message('Custom message')->response();

api()->validationError('Validation failed', $validator->errors()->toArray())->response();

$users = User::paginate(15);

return api()->success()
            ->records($users)
            ->response();

return api()->success()
            ->records($users, total: 120, page: 2, pageSize: 15)
            ->response();

api()->success()
     ->withCookie(cookie('token', $token, 60))
     ->withoutCookie('old_session')
     ->response();

// config/api-response.php
return [
    'keys' => [
        'status'  => 'status',   // default: 'status'
        'code'    => 'code',     // default: 'code'
        'message' => 'message',  // default: 'message'
        'data'    => 'data',     // default: 'data'
    ],
];

use DantePiazza\LaravelApiResponse\ApiResponse;

ApiResponse::macro('teapot', function () {
    return $this->set(ApiResponse::STATUS_FAIL, 418, "I'm a teapot");
});

// Then anywhere:
api()->teapot()->response();
bash
php artisan vendor:publish --tag=api-response-config