PHP code example of hardcodear / api-response-service

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

    

hardcodear / api-response-service example snippets




use Illuminate\Http\Request;

class UserController
{
  public function index()
  {
    return apiresponse()->success('Listado de usuarios', [
      ['id' => 1, 'name' => 'Ana'],
      ['id' => 2, 'name' => 'Luis'],
    ]);
  }

  public function store(Request $request)
  {
    $errors = [];

    if (! $request->input('email')) {
      $errors['email'][] = 'El campo email es obligatorio.';
    }

    if ($errors !== []) {
      return apiresponse()->validation('Datos inválidos', $errors);
    }

    return apiresponse()->success('Usuario creado', ['id' => 123]);
  }
}

apiresponse()->success(string $mensaje = null, mixed $data = null)

return apiresponse()->success('Operación realizada con éxito', ['id' => 123]);

apiresponse()->notFound(string $mensaje = null, mixed $errores = null)

return apiresponse()->notFound('Recurso no encontrado');

apiresponse()->validation(string $mensaje = null, mixed $errores = null)

return apiresponse()->validation('Datos inválidos', $validator->errors());

apiresponse()->unauthorized(string $mensaje = null, mixed $errores = null)

return apiresponse()->unauthorized('Token inválido');

apiresponse()->forbidden(string $mensaje = null, mixed $errores = null)

return apiresponse()->forbidden('Acceso denegado');

apiresponse()->serverError(string $mensaje = null, mixed $errores = null)

return apiresponse()->serverError('Error inesperado');

apiresponse()->error(string $mensaje = null, mixed $errores = null)

return apiresponse()->error('Error inesperado', ['detalle' => '...']);

use Hardcodear\ApiResponseService\ExceptionApiRegistrar;
use Illuminate\Foundation\Configuration\Exceptions;

$app->withExceptions(function (Exceptions $exceptions) {
    ExceptionApiRegistrar::bind($exceptions);
});
json
{
  "status": 500,
  "message": "Mensaje de error",
  "errors": [
    // array de errores
  ]
}
bash
php artisan vendor:publish --tag=apiresponse-config