Weave Code
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

php-standard-library/json provides JSON encode/decode helpers with sensible defaults and typed exceptions. Safer, clearer error handling than native json_encode/json_decode, ideal for consistent JSON handling in PHP apps and libraries.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/json
    

    For Laravel, register the service provider in config/app.php:

    'providers' => [
        PhpStandardLibrary\Json\JsonServiceProvider::class,
    ],
    
  2. First Use Case: Replace native json_encode()/json_decode() with the package’s methods:

    // Encode with sensible defaults (throws on error)
    $json = Json::encode(['key' => 'value']);
    
    // Decode with strict validation
    $data = Json::decode($json);
    
  3. Configuration: Publish the config file:

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

    Customize config/json.php to set default flags (e.g., JSON_THROW_ON_ERROR, JSON_PRETTY_PRINT).


Implementation Patterns

Usage Patterns

  1. Consistent JSON Handling in Controllers:

    // Laravel controller example
    public function store(Request $request)
    {
        $validated = Json::decode($request->json(), Json::THROW_ON_ERROR);
        $data = Json::encode($validated, JSON_PRETTY_PRINT);
        return response()->json($data);
    }
    
  2. API Response Standardization: Use the package to enforce consistent JSON formatting across all responses:

    // AppServiceProvider boot method
    Response::macro('jsonStandard', function ($data) {
        return response()->json(Json::encode($data, JSON_PRETTY_PRINT));
    });
    
  3. Request Validation: Validate incoming JSON payloads with schema validation:

    public function rules()
    {
        return [
            'payload' => 'required|json',
        ];
    }
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $schema = file_get_contents('schemas/api.json');
            Json::validate($this->payload, $schema);
        });
    }
    
  4. CLI/Artisan Commands: Use the package for JSON formatting in CLI tools:

    $data = Json::decode(file_get_contents('data.json'));
    $prettyJson = Json::encode($data, JSON_PRETTY_PRINT);
    file_put_contents('output.json', $prettyJson);
    
  5. Testing: Standardize JSON assertions in PHPUnit tests:

    public function testJsonResponse()
    {
        $response = $this->get('/api/data');
        $data = Json::decode($response->getContent());
        $this->assertArrayHasKey('key', $data);
    }
    

Workflows

  1. Laravel Request/Response Pipeline:

    • Request: Decode JSON payloads in middleware or FormRequest classes.
    • Response: Encode JSON responses with consistent flags (e.g., JSON_PRETTY_PRINT for debugging).
  2. Database JSON Columns: Use the package for Eloquent model serialization:

    protected $casts = [
        'metadata' => 'json',
    ];
    // Custom accessor/mutator
    public function getMetadataAttribute($value)
    {
        return Json::decode($value);
    }
    public function setMetadataAttribute($value)
    {
        $this->attributes['metadata'] = Json::encode($value);
    }
    
  3. Event Handling: Serialize/deserialize JSON in event listeners:

    public function handle(ApiRequestEvent $event)
    {
        $data = Json::decode($event->payload);
        // Process data...
        $response = Json::encode($data);
        $event->setResponse($response);
    }
    

Integration Tips

  1. Leverage Laravel Facades: Use Json::laravel() for Laravel-specific features (e.g., config-driven flags):

    $json = Json::laravel()->encode($data);
    
  2. Custom Exceptions: Extend Laravel’s exception handler to log JsonException:

    public function register()
    {
        $this->reportable(function (JsonException $e) {
            Log::error('JSON Error', [
                'exception' => $e,
                'data' => $e->getData(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);
        });
    }
    
  3. Configuration-Driven Flags: Centralize JSON encoding/decoding flags in config/json.php:

    return [
        'default_flags' => JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
        'pretty_print' => env('APP_DEBUG', false) ? JSON_PRETTY_PRINT : 0,
    ];
    

    Then use them in your code:

    $flags = config('json.default_flags') | config('json.pretty_print');
    $json = Json::encode($data, $flags);
    
  4. Schema Validation: Integrate with Laravel’s validation pipeline:

    public function rules()
    {
        return [
            'payload' => ['required', 'json', function ($attribute, $value, $fail) {
                $schema = file_get_contents('schemas/' . $this->route('schema'));
                if (!Json::validate($value, $schema)->isValid()) {
                    $fail('The ' . $attribute . ' does not match the required schema.');
                }
            }],
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Facade Namespace Changes:

    • Issue: The package may rename facades (e.g., Json::encode()Json::laravel()->encode()).
    • Fix: Use aliases in config/app.php or update all usages:
      'aliases' => [
          'Json' => App\Providers\JsonServiceProvider::class . '::jsonAlias',
      ],
      
  2. Deprecated Methods:

    • Issue: Methods like Json::pretty() may be deprecated.
    • Fix: Replace with explicit flags:
      // Old
      $json = Json::pretty($data);
      // New
      $json = Json::encode($data, JSON_PRETTY_PRINT);
      
  3. Validation Overhead:

    • Issue: Schema validation (Json::validate()) adds runtime overhead.
    • Fix: Disable in production for non-critical paths:
      if (config('json.validate.enabled')) {
          Json::validate($data, $schema);
      }
      
  4. Dependency Conflicts:

    • Issue: Schema validation may require symfony/validator or webonyx/graphql-php.
    • Fix: Check composer.json for conflicts and update dependencies accordingly.
  5. Error Handling:

    • Issue: Json::decode() throws JsonException by default (due to JSON_THROW_ON_ERROR).
    • Fix: Catch exceptions and handle gracefully:
      try {
          $data = Json::decode($json);
      } catch (JsonException $e) {
          return response()->json(['error' => 'Invalid JSON'], 400);
      }
      

Debugging Tips

  1. Log JSON Errors: Extend Laravel’s exception handler to log detailed JsonException info:

    public function report(Throwable $exception)
    {
        if ($exception instanceof JsonException) {
            Log::error('JSON Decoding Error', [
                'message' => $exception->getMessage(),
                'data' => $exception->getData(),
                'context' => $exception->getContext(),
            ]);
        }
        parent::report($exception);
    }
    
  2. Validate JSON Schema: Use the package’s validation to debug malformed JSON:

    $validator = Json::validate($data, $schema);
    if (!$validator->isValid()) {
        dd($validator->getErrors()); // Debug validation errors
    }
    
  3. Check Config Values: Ensure config/json.php is correctly published and configured:

    php artisan config:clear
    php artisan vendor:publish --tag=json-config --force
    
  4. Test Edge Cases: Validate the package’s behavior with edge cases:

    // Test recursive structures
    $recursiveData = ['key' => ['nested' => &$recursiveData]];
    try {
        Json::encode($recursiveData);
    } catch (JsonException $e) {
        // Expected behavior: catch and handle
    }
    

Extension Points

  1. Custom JSON Flags: Extend the package to support custom flags or defaults:

    // In a service provider
    Json::extend(function ($encoder) {
        $encoder->addFlag('CUSTOM_FLAG', JSON_UNESCAPED_UNICODE);
    });
    
  2. Schema Validation Rules: Create reusable validation rules for Laravel’s validator:

    use Illuminate\Validation\Rule;
    
    Rule::macro('jsonSchema', function ($schemaPath) {
        return function ($attribute, $value, $
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai