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

Reference Region Laravel Package

baks-dev/reference-region

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require baks-dev/reference-region

Ensure your composer.json has "php": "^8.4" in require.

  1. Publish Config (if needed):

    php artisan vendor:publish --provider="BaksDev\ReferenceRegion\ReferenceRegionServiceProvider" --tag="config"
    

    Check config/reference-region.php for default settings.

  2. First Use Case: Fetch a region by ID (e.g., for a dropdown or API response):

    use BaksDev\ReferenceRegion\Facades\ReferenceRegion;
    
    $region = ReferenceRegion::find(73); // Replace 73 with a valid region ID
    dd($region->name); // Output: e.g., "Москва"
    
  3. Key Classes:

    • ReferenceRegion facade (main entry point).
    • Region model (extends Illuminate\Database\Eloquent\Model).
    • RegionRepository (handles data logic; extend for custom queries).
  4. Where to Look First:

    • Facade: app/Facades/ReferenceRegion.php (if extending).
    • Config: config/reference-region.php (adjust caching, sources, etc.).
    • Migrations: database/migrations/ (if customizing the regions table).
    • Tests: tests/Feature/ (for edge cases like caching or API responses).

Implementation Patterns

Core Workflows

1. Fetching Regions

  • Basic Fetch:
    // Get all regions (cached by default)
    $regions = ReferenceRegion::all();
    
    // Get regions for a specific parent (e.g., federal districts)
    $federalDistricts = ReferenceRegion::whereParentId(null)->get();
    
  • Lazy Loading: Use cursor() for large datasets:
    foreach (ReferenceRegion::cursor() as $region) {
        // Process without loading all into memory
    }
    

2. Integration with Eloquent

  • Polymorphic Relations: Attach regions to other models:
    class City extends Model {
        public function region() {
            return $this->belongsTo(Region::class);
        }
    }
    
  • Query Scopes: Add custom scopes to the Region model:
    // In app/Models/Region.php
    public function scopeActive($query) {
        return $query->where('is_active', true);
    }
    
    Usage:
    $activeRegions = ReferenceRegion::active()->get();
    

3. Caching Strategies

  • Default Caching: The package caches regions for 24 hours by default (config/reference-region.php). Clear cache manually:
    ReferenceRegion::clearCache();
    
  • Custom Cache Keys: Override the cache key in config:
    'cache_key' => 'custom_region_cache',
    

4. API Responses

  • Transformers: Use spatie/array-to-xml or spatie/laravel-data for structured responses:
    use Spatie\Data\Data;
    
    class RegionResource extends Data {
        public function __construct(public string $name, public ?string $parentName) {}
    }
    
    $resource = new RegionResource($region->name, $region->parent?->name);
    return response()->json($resource);
    

5. Admin Panels (e.g., Nova, Filament)

  • Nova Integration: Extend the Region model for Nova:
    // In app/Nova/Region.php
    public static $search = [
        'id', 'name', 'parent_id',
    ];
    
  • Filament Integration: Use the Table component:
    use Filament\Tables;
    
    Tables::column('name')->searchable();
    

6. Custom Data Sources

  • Override Repository: Bind a custom repository in a service provider:
    $this->app->bind(
        \BaksDev\ReferenceRegion\Contracts\RegionRepository::class,
        \App\Repositories\CustomRegionRepository::class
    );
    
    Implement RegionRepository interface to modify logic.

7. Localization

  • Translatable Names: Use spatie/laravel-translatable to store names in multiple languages:
    class Region extends Model {
        use \Spatie\Translatable\HasTranslations;
    
        public $translatable = ['name'];
    }
    
    Fetch translated names:
    $region->getTranslation('name', 'ru');
    

8. Events and Observers

  • Listen for Region Updates:
    // In EventServiceProvider
    protected $listen = [
        \BaksDev\ReferenceRegion\Events\RegionUpdated::class => [
            \App\Listeners\LogRegionChange::class,
        ],
    ];
    

Integration Tips

Laravel Features

  • Service Container: Bind interfaces to custom implementations for testing:
    $this->app->when(ReferenceRegion::class)
        ->needs(\BaksDev\ReferenceRegion\Contracts\RegionRepository::class)
        ->give(\App\Repositories\MockRegionRepository::class);
    
  • Middleware: Restrict region access in middleware:
    public function handle($request, Closure $next) {
        if (!$request->user()->can('view_regions')) {
            abort(403);
        }
        return $next($request);
    }
    
  • Commands: Create a command to sync regions from an external API:
    use BaksDev\ReferenceRegion\Facades\ReferenceRegion;
    
    class SyncRegionsCommand extends Command {
        protected $signature = 'regions:sync';
        public function handle() {
            $data = Http::get('https://api.example.com/regions')->json();
            foreach ($data as $item) {
                Region::updateOrCreate(['id' => $item['id']], $item);
            }
            $this->info('Regions synced!');
        }
    }
    

Testing

  • Mocking the Facade:
    $this->mock(\BaksDev\ReferenceRegion\Facades\ReferenceRegion::class)
         ->shouldReceive('find')
         ->andReturn(new Region(['name' => 'Test Region']));
    
  • Feature Tests: Test caching behavior:
    public function test_region_caching() {
        $region = ReferenceRegion::find(1);
        cache()->shouldReceive('get')->once();
        $this->assertEquals('Cached Region', $region->name);
    }
    

Gotchas and Tips

Pitfalls

1. Cache Invalidation

  • Issue: Forgetting to clear cache after manual region updates.
  • Fix: Call ReferenceRegion::clearCache() after bulk updates or use events:
    // In RegionObserver
    public function saved(Model $model) {
        ReferenceRegion::clearCache();
    }
    
  • Tip: Use cache()->forget() with the config cache_key for granular control.

2. Parent-Child Relationships

  • Issue: Infinite recursion when fetching nested regions without depth limits.
  • Fix: Use withDepth() or limit recursion in the repository:
    // In RegionRepository
    public function withChildren($region, $depth = 0, $maxDepth = 3) {
        if ($depth >= $maxDepth) return $region;
        $region->children = $this->newQuery()->where('parent_id', $region->id)->get();
        return $this->withChildren($region, $depth + 1, $maxDepth);
    }
    

3. Database Schema Mismatches

  • Issue: Custom migrations altering the regions table structure.
  • Fix: Publish and extend the original migrations:
    php artisan vendor:publish --tag="migrations"
    
    Then modify database/migrations/[timestamp]_create_regions_table.php.

4. Facade vs. Direct Model Usage

  • Issue: Overusing the facade for complex queries, leading to untestable code.
  • Fix: Prefer injecting RegionRepository or the Region model directly into services:
    public function __construct(private RegionRepository $regionRepo) {}
    

5. Performance with Large Datasets

  • Issue: Slow queries when fetching regions with deep relationships.
  • Fix:
    • Use select() to limit columns:
      Region::select('id', 'name', 'parent_id')->get();
      
    • Add indexes to parent_id and frequently queried fields.

6. Time Zone Handling

  • Issue: Region data fetched at different times due to caching.
  • Fix: Set a consistent now() in the repository:
    public function now() {
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor