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

Array Dot Laravel Package

flow-php/array-dot

Flow PHP Array Dot adds easy dot-notation access to PHP arrays. Read, set, and manipulate deeply nested values with a clean API—ideal for config data, decoded JSON, and complex structures—making array handling clearer and less error-prone.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require flow-php/array-dot
    

    No Laravel-specific setup required—works as a standalone package.

  2. First Use Case: Replace verbose nested array access with dot notation:

    use Flow\ArrayDot\ArrayDot;
    
    $array = [
        'user' => [
            'name' => 'John',
            'address' => [
                'city' => 'New York'
            ]
        ]
    ];
    
    $dot = new ArrayDot($array);
    echo $dot->get('user.address.city'); // Output: "New York"
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. Dot Notation Access:

    • Get Values:
      $value = $dot->get('path.to.value', 'default');
      
    • Set Values:
      $dot->set('path.to.value', 'new_value');
      
    • Check Existence:
      if ($dot->has('path.to.value')) { ... }
      
  2. Laravel Integration:

    • Service Provider Binding:
      $this->app->singleton('array-dot', fn() => new ArrayDot());
      
    • Facade Wrapper (create ArrayDotFacade.php):
      use Illuminate\Support\Facades\Facade;
      class ArrayDotFacade extends Facade { protected static function getFacadeAccessor() { return 'array-dot'; } }
      
      Usage:
      ArrayDot::get('request.user.id');
      
  3. ETL Workflows:

    • Transform Nested Arrays:
      $data = array_dot::transform($array, fn($value, $path) => strtoupper($value));
      
    • Flatten/Unflatten:
      $flat = array_dot::flatten($nestedArray);
      $nested = array_dot::unflatten($flatArray);
      
  4. Request/Response Handling:

    • Middleware for Dot-Notation Requests:
      public function handle($request, Closure $next) {
          $request->merge(array_dot::dot($request->all()));
          return $next($request);
      }
      
    • API Responses:
      return response()->json(array_dot::dot($eloquentData));
      
  5. Validation:

    • Dynamic Rules:
      $rules = [
          'user.address.city' => 'required|string',
          'user.profile.*'    => 'nullable'
      ];
      

Workflows

  1. Data Migration:

    • Convert legacy nested arrays to dot notation for consistency:
      $migrated = array_dot::dot($legacyArray, ['user', 'address']);
      
  2. Configuration Management:

    • Merge environment-specific configs:
      $defaultConfig = require 'config/default.php';
      $envConfig = require 'config/env.php';
      $merged = array_dot::merge($defaultConfig, $envConfig);
      
  3. Testing:

    • Assert nested values concisely:
      $this->assertEquals('New York', array_dot::get($data, 'user.address.city'));
      

Integration Tips

  1. Combine with Laravel’s Arr:

    • Use array_dot for complex operations, Arr::dot() for simple cases:
      use Illuminate\Support\Arr;
      Arr::set($array, 'user.address.city', 'Boston'); // Simple
      array_dot::set($array, 'user.address.city', 'Boston'); // Complex paths
      
  2. Performance Optimization:

    • Cache dot-path operations in loops:
      $cache = [];
      foreach ($largeArray as $item) {
          $cache[$item['id']] = array_dot::get($item, 'user.profile.name');
      }
      
  3. Immutable Operations:

    • Use array_dot::dot() + array_merge for immutability:
      $newArray = array_merge($original, array_dot::dot($original, ['path', 'to', 'update']));
      

Gotchas and Tips

Pitfalls

  1. Overwriting vs. Merging:

    • set() overwrites by default. Use merge() for partial updates:
      // Overwrites entire 'address' key
      $dot->set('user.address', ['city' => 'Boston']);
      
      // Merges with existing 'address'
      $dot->merge('user.address', ['city' => 'Boston']);
      
  2. Circular References:

    • The package doesn’t handle circular references. Add validation:
      if (array_dot::hasCircularReferences($array)) {
          throw new \RuntimeException('Circular reference detected');
      }
      
  3. Non-Array Inputs:

    • Throws exceptions for non-array inputs. Validate first:
      if (!is_array($data)) {
          $data = [];
      }
      
  4. PHP 8.3+ Requirement:

    • Fails on older PHP versions. Use a polyfill or feature flag:
      if (version_compare(PHP_VERSION, '8.3.0') < 0) {
          throw new \RuntimeException('PHP 8.3+ required');
      }
      
  5. Performance with Deep Arrays:

    • Recursive dot-path resolution can be slow for very deep arrays (>10 levels). Benchmark:
      $start = microtime(true);
      array_dot::get($deepArray, 'a.b.c.d.e.f');
      $time = microtime(true) - $start;
      

Debugging

  1. Invalid Dot Paths:

    • Returns null silently. Add logging:
      $value = array_dot::get($array, 'invalid.path');
      if ($value === null) {
          \Log::warning("Dot path 'invalid.path' not found");
      }
      
  2. Unexpected Mutations:

    • set()/merge() modifies the original array. Use dot() for immutable copies:
      $immutable = array_dot::dot($originalArray);
      array_dot::set($immutable, 'path', 'value');
      
  3. Case Sensitivity:

    • Dot paths are case-sensitive ('User.Name''user.name'). Normalize keys if needed:
      $normalized = array_dot::transform($array, fn($v, $k) => strtolower($k), true);
      

Tips

  1. Laravel-Specific Extensions:

    • Create a custom trait for Eloquent models:
      trait DotAccessible {
          public function getDotAttribute($key) {
              return array_dot::get($this->attributes, $key);
          }
      }
      
  2. Wildcards:

    • Use * for partial matches (e.g., 'user.*'). Combine with array_dot::filter():
      $filtered = array_dot::filter($array, fn($path) => str_contains($path, 'user.'));
      
  3. Configuration:

    • Override defaults in a service provider:
      $this->app->when(ArrayDot::class)
          ->needs('$strict')
          ->give(true); // Enable strict mode
      
  4. Testing:

    • Mock ArrayDot in PHPUnit:
      $mock = $this->createMock(ArrayDot::class);
      $mock->method('get')->willReturn('mocked_value');
      
  5. Alternatives:

    • For Laravel-specific needs, consider Illuminate\Support\Arr::dot() for simpler cases:
      Arr::set($array, 'user.address.city', 'Boston'); // Built-in
      array_dot::set($array, 'user.address.city', 'Boston'); // Advanced
      
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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