Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Laravel Package

php-standard-library/json

A small PHP Standard Library package for JSON encoding and decoding with typed exceptions and sensible defaults, providing predictable error handling for safer serialization in Laravel and other PHP projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require php-standard-library/json
    
  2. Publish Config:

    php artisan vendor:publish --provider="PhpStandardLibrary\Json\JsonServiceProvider" --tag="json-config"
    

    This creates config/json.php with sensible defaults (e.g., JSON_THROW_ON_ERROR enabled in development).

  3. First Use Case: API Response Replace response()->json() in a controller:

    use PhpStandardLibrary\Json\Facades\Json;
    
    public function show(User $user) {
        return response()->json(Json::laravel()->encode($user->toArray()));
    }
    

Key Starting Points

  • Facade: Json::laravel() – Laravel-specific entry point with config awareness.
  • Config: config/json.php – Centralize flags like JSON_PRETTY_PRINT or JSON_THROW_ON_ERROR.
  • Exceptions: JsonException – Catches parsing errors with context (e.g., line numbers).

Implementation Patterns

Core Workflows

1. API Request/Response

  • Request Parsing (Middleware):
    public function handle(Request $request, Closure $next) {
        $data = Json::laravel()->decode($request->getContent());
        $request->merge($data); // Merge into request object
        return $next($request);
    }
    
  • Response Formatting:
    return response()->json(
        Json::laravel()->encode($data, pretty: env('APP_DEBUG'))
    );
    

2. Validation Integration

  • Schema Validation (e.g., JSON Schema):
    use PhpStandardLibrary\Json\Validation\JsonSchemaValidator;
    
    $schema = file_get_contents('schemas/user.json');
    Json::validate($request->json()->all(), $schema);
    
  • Laravel Validator:
    $validator = Validator::make($data, [
        'name' => 'required|string',
        'metadata' => function ($attribute, $value, $fail) {
            Json::validate($value, file_get_contents('schemas/metadata.json'));
        },
    ]);
    

3. CLI/Artisan Commands

  • Pretty-print JSON for logs:
    $this->line(Json::laravel()->encode($data, pretty: true));
    

4. Database/ORM

  • Eloquent JSON Columns:
    protected $casts = ['metadata' => 'json'];
    
    public function getMetadataAttribute($value) {
        return Json::laravel()->decode($value);
    }
    

Integration Tips

  • Service Providers: Bind custom JSON encoders/decoders:
    $this->app->bind('json.encoder', function () {
        return new CustomJsonEncoder();
    });
    
  • Middleware: Validate JSON structure in App\Http\Middleware\ValidateJson:
    public function handle($request, Closure $next) {
        Json::validate($request->json()->all(), $this->schema);
        return $next($request);
    }
    
  • Testing: Mock Json::laravel() in PHPUnit:
    $this->mock(Json::class)->shouldReceive('encode')->andReturn('{}');
    

Gotchas and Tips

Pitfalls

  1. Facade Migration:

    • Issue: Json::encode() → Json::laravel()->encode() breaks existing code.
    • Fix: Add an alias in AppServiceProvider:
      Json::extend('laravel', function () {
          return new JsonFacade();
      });
      
  2. Deprecated Methods:

    • Issue: Json::pretty() is deprecated.
    • Fix: Use flags explicitly:
      Json::laravel()->encode($data, JSON_PRETTY_PRINT);
      
  3. Validation Overhead:

    • Issue: Json::validate() slows down high-traffic APIs.
    • Fix: Disable in config/json.php:
      'validation' => [
          'enabled' => env('APP_ENV') !== 'production',
      ],
      
  4. Circular References:

    • Issue: Native json_encode fails on circular references.
    • Fix: Use JSON_THROW_ON_ERROR and handle manually, or switch to Symfony Serializer.
  5. Config Overrides:

    • Issue: Global config (config/json.php) may conflict with per-request needs.
    • Fix: Pass flags explicitly:
      Json::laravel()->encode($data, JSON_THROW_ON_ERROR, JSON_UNESCAPED_SLASHES);
      

Debugging Tips

  • Exception Context:

    • JsonException includes $e->getData() and $e->getContext() for debugging malformed JSON.
    • Log in App\Exceptions\Handler:
      Log::error('JSON Error', [
          'exception' => $e,
          'data' => $e->getData(),
      ]);
      
  • Pretty-Printing:

    • Use JSON_PRETTY_PRINT for logs:
      Log::debug(Json::laravel()->encode($data, JSON_PRETTY_PRINT));
      
  • Performance:

    • Benchmark JSON_THROW_ON_ERROR vs. JSON_BIGINT_AS_STRING for large payloads.

Extension Points

  1. Custom Encoders/Decoders:

    • Implement JsonEncoderInterface and bind in AppServiceProvider:
      $this->app->bind('json.encoder', function () {
          return new CustomEncoder();
      });
      
  2. Schema Validation:

    • Extend JsonSchemaValidator for custom rules:
      class CustomValidator extends JsonSchemaValidator {
          public function validate($data, $schema) {
              // Custom logic
          }
      }
      
  3. Laravel Facade:

    • Override Json::laravel() behavior:
      Json::extend('custom', function () {
          return new CustomJsonService();
      });
      
  4. Event Listeners:

    • Hook into json.encoded/json.decoded events for logging/auditing:
      event(new JsonEncoded($data, $encodedJson));
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log