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

Iran Regions Laravel Package

shimadotdev/iran-regions

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation: Run composer require shimadotdev/iran-regions and publish migrations with php artisan iran-regions:install.
  2. First Use Case: Access provinces/cities via the Iran facade:
    use Shimadotdev\IranRegions\Iran;
    
    // Get Tehran province
    $tehran = Iran::province()->where('slug', 'tehran')->first();
    
    // Get all cities in Tehran with eager-loaded relations
    $tehranCities = Iran::city()->where('province_id', $tehran->id)->with('province')->get();
    
  3. Key Files: Focus on:
    • app/Models/Province.php and app/Models/City.php (auto-generated after installation).
    • resources/lang/{fa,en}/iranRegions.php for localization.

Implementation Patterns

Core Workflows

  1. Hierarchical Queries:
    // Get all active cities in a province
    $activeCities = Iran::city()
        ->where('province_id', $province->id)
        ->where('is_active', 1)
        ->with('province')
        ->get();
    
  2. Geospatial Filtering (via Laravel Scout or custom logic):
    // Find cities within 50km of a point (pseudo-code)
    $nearbyCities = Iran::city()
        ->whereBetween('latitude', [$lat - 0.5, $lat + 0.5])
        ->whereBetween('longitude', [$lng - 0.5, $lng + 0.5])
        ->get();
    
  3. Localization:
    // Switch between Persian/English names dynamically
    $name = app()->getLocale() === 'fa'
        ? trans("iranRegions::provinces.{$province->slug}")
        : $province->name;
    

Integration Tips

  • Model Relations: Extend your models to use the package’s data:
    // In User.php
    public function province()
    {
        return $this->belongsTo(Province::class, 'province_id');
    }
    
  • Form Validation: Use the slugs for consistent data entry:
    use Shimadotdev\IranRegions\Rules\ValidProvince;
    
    $request->validate([
        'province' => ['required', new ValidProvince],
    ]);
    
  • API Responses: Normalize geographic data in JSON:
    return response()->json([
        'user' => $user,
        'location' => [
            'province' => $user->province->slug,
            'city' => $user->city?->slug,
        ],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Slug vs. Name Confusion:
    • Always use slug for queries (e.g., where('slug', 'tehran')), not name (case-sensitive and may change).
    • Fix: Cache slug-to-name mappings if performance is critical.
  2. Missing Migrations:
    • If iran-regions:install fails, manually run:
      php artisan migrate
      
  3. Geolocation Precision:
    • Latitude/longitude are approximate (suitable for regional filtering, not GPS-level accuracy).
    • Workaround: Use a dedicated geocoding service for high-precision needs.

Debugging

  1. Relation Issues:
    • Verify the province_id/city_id foreign keys exist in your database.
    • Check for reserved column names (e.g., id conflicts with Laravel’s default).
  2. Localization Errors:
    • Ensure language files are published:
      php artisan vendor:publish --tag=iran-regions-lang
      
    • Validate the slug structure in resources/lang/{fa,en}/iranRegions.php matches the database.

Extension Points

  1. Custom Queries:
    • Extend the Province/City models with scopes:
      // In Province.php
      public function scopeByCallingCode($query, $code)
      {
          return $query->where('calling_code', $code);
      }
      
  2. Dynamic Data:
    • Override the seeder to add custom fields (e.g., population):
      // In DatabaseSeeder.php
      Iran::city()->update(['population' => 1000000]); // Example
      
  3. API Endpoints:
    • Create a controller to expose filtered data:
      // routes/api.php
      Route::get('/provinces/{slug}/cities', [CityController::class, 'index']);
      
  4. Testing:
    • Use the package’s factories in tests:
      $province = Province::factory()->create();
      $city = City::factory()->for($province)->create();
      

```markdown
### **Pro Tips for Daily Use**
- **Eager Loading**: Always use `with()` to avoid N+1 queries when fetching relations:
  ```php
  $users = User::with(['province.cities'])->get();
  • Caching: Cache frequent queries (e.g., all provinces):
    $provinces = Cache::remember('all-provinces', now()->addHours(1), function() {
        return Iran::province()->get();
    });
    
  • Validation Rules: Reuse the package’s rules for forms:
    use Shimadotdev\IranRegions\Rules\ValidCity;
    
    $request->validate([
        'city' => ['required', new ValidCity],
    ]);
    
  • Localization Shortcuts: Create a helper for quick name lookups:
    // In AppServiceProvider
    function provinceName($slug, $locale = 'fa')
    {
        return trans("iranRegions::provinces.{$slug}");
    }
    
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.
terminal42/code-quality-tools
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