PHP code example of renslabs / laravel-api-response-formatter

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

    

renslabs / laravel-api-response-formatter example snippets




use renslabs\ApiResponseFormatter\ApiResponse;

class UserController extends Controller
{
    public function show($id): JsonResponse
    {
        $user = User::find($id);

        if ($user) {
            return ApiResponse::success($user);
        } else {
            return ApiResponse::notFound(null, 'User not found');
        }
    }

    public function create(Request $request): JsonResponse
    {
        // Validation logic

        if ($validationFails) {
            return ApiResponse::failedValidation($validationErrors);
        }

        $user = User::create($request->all());

        return ApiResponse::created($user);
    }
}

use Illuminate\Support\Facades\Log;
use OpenTelemetry\API\Trace\Span;

$context = Span::getCurrent()->getContext();
$logContext = ['order_id' => $order->id];

if ($context->isValid()) {
    $logContext['trace_id'] = $context->getTraceId();
    $logContext['span_id'] = $context->getSpanId();
}

Log::info('Order created', $logContext);
bash
php artisan vendor:publish --tag=api-response-formatter-config
dotenv
OTEL_PHP_AUTOLOAD_ENABLED=true
OTEL_SERVICE_NAME=my-laravel-api
OTEL_TRACES_EXPORTER=otlp
OTEL_METRICS_EXPORTER=none
OTEL_LOGS_EXPORTER=none
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.<region>.signoz.cloud:443
OTEL_EXPORTER_OTLP_HEADERS=signoz-ingestion-key=<your-ingestion-key>
OTEL_PROPAGATORS=baggage,tracecontext