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

Laravel Addresses Laravel Package

rinvex/laravel-addresses

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require rinvex/laravel-addresses
    php artisan rinvex:publish:addresses
    php artisan migrate
    
    • Focus on the rinvex_addresses table and its relationship with your models.
  2. First Use Case: Attach an address to a User model:

    use Rinvex\Addresses\Traits\HasAddresses;
    
    class User extends Model
    {
        use HasAddresses;
    }
    
    // In a controller or service:
    $user = User::find(1);
    $user->addresses()->create([
        'addressable_type' => 'App\Models\User',
        'addressable_id' => $user->id,
        'address' => '123 Main St',
        'city' => 'Metropolis',
        'postal_code' => '10001',
        'country' => 'USA'
    ]);
    
  3. Key Files:

    • config/addresses.php: Customize default fields or behaviors.
    • app/Models/Address.php: Extend or modify the base Address model.

Implementation Patterns

Core Workflows

  1. Polymorphic Address Attachment:

    • Use HasAddresses trait on any Eloquent model (e.g., User, Vendor, Store).
    • Example for a Vendor:
      class Vendor extends Model
      {
          use HasAddresses;
      }
      
    • Attach addresses via:
      $vendor->addresses()->create([...]);
      
  2. Querying Addresses:

    • Fetch all addresses for a model:
      $user->addresses; // Collection of Address models
      
    • Filter by address type (e.g., "home", "work"):
      $user->addresses()->where('type', 'home')->get();
      
    • Global search (using scopes):
      $results = Address::search('Main St')->get();
      
  3. Validation:

    • Leverage Laravel’s built-in validation or extend the Address model’s rules() method:
      // app/Models/Address.php
      public static function rules()
      {
          return [
              'address' => 'required|string|max:255',
              'postal_code' => 'required|string|size:5',
              // ...
          ];
      }
      
  4. API/Forms Integration:

    • Use rinvex/laravel-addresses with Form Requests or API Resources:
      // Example API Resource
      public function toArray($request)
      {
          return [
              'addresses' => $this->addresses->map(function ($address) {
                  return $address->only(['address', 'city', 'postal_code']);
              }),
          ];
      }
      
  5. Custom Fields:

    • Extend the addresses table via migrations or use the config/addresses.php to add custom fields:
      // config/addresses.php
      'fields' => [
          'address',
          'city',
          'postal_code',
          'country',
          'type', // e.g., 'home', 'work'
          'latitude', // Custom field
          'longitude',
      ],
      

Integration Tips

  1. Geocoding:

    • Add latitude/longitude via a creating observer or service:
      $address->geocode(); // Hypothetical method; use a service like Google Maps API.
      
  2. Soft Deletes:

    • Enable soft deletes for Address model:
      use SoftDeletes;
      
      class Address extends Model
      {
          use SoftDeletes, HasAddresses;
      }
      
    • Update migrations to include deleted_at.
  3. Localization:

    • Localize address fields (e.g., street, city) using Laravel’s localization features or a package like spatie/laravel-translatable.
  4. Testing:

    • Use factory patterns to seed test addresses:
      $user = User::factory()->create();
      $user->addresses()->create([...]);
      
    • Test polymorphic relationships:
      $this->assertCount(1, $user->addresses);
      

Gotchas and Tips

Pitfalls

  1. Polymorphic Relationships:

    • Issue: Forgetting to set addressable_type and addressable_id manually.
    • Fix: Use the HasAddresses trait’s built-in methods to avoid manual assignment:
      $user->addAddress([...]); // Automatically sets polymorphic keys.
      
  2. Migration Conflicts:

    • Issue: Custom migrations for the addresses table may conflict with published ones.
    • Fix: Always run php artisan rinvex:publish:addresses --force to overwrite existing files.
  3. Performance:

    • Issue: N+1 queries when eager-loading addresses.
    • Fix: Use with() or load():
      $users = User::with('addresses')->get();
      
  4. Abandoned Package:

    • Issue: No active maintenance or updates.
    • Mitigation:
      • Fork the repo and maintain it yourself.
      • Consider alternatives like laravel-address or build a custom solution.
  5. Validation Overrides:

    • Issue: Default validation may not fit your use case.
    • Fix: Override the rules() method in your Address model or use Form Requests.

Debugging

  1. Missing Addresses:

    • Check if the HasAddresses trait is properly used and the model is saved before attaching addresses.
    • Verify polymorphic keys (addressable_type, addressable_id) are set.
  2. Query Issues:

    • Use toSql() and dd() to inspect generated queries:
      $query = $user->addresses()->where('city', 'Metropolis');
      \Log::info($query->toSql(), $query->getBindings());
      
  3. Configuration Errors:

    • Ensure config/addresses.php is properly published and configured:
      'model' => \Rinvex\Addresses\Models\Address::class,
      'fields' => [...],
      

Extension Points

  1. Custom Address Types:

    • Extend the Address model to support custom types (e.g., "billing", "shipping"):
      // app/Models/Address.php
      protected $casts = [
          'type' => 'string',
      ];
      
  2. Observers:

    • Add logic before/after address creation:
      Address::observe(AddressObserver::class);
      
      class AddressObserver
      {
          public function creating(Address $address)
          {
              $address->type = request('type', 'home');
          }
      }
      
  3. Scopes:

    • Add reusable query scopes:
      // app/Models/Address.php
      public function scopeInCountry($query, $country)
      {
          return $query->where('country', $country);
      }
      
      Usage:
      Address::inCountry('USA')->get();
      
  4. API Resources:

    • Create dedicated resources for addresses:
      public function toArray($request)
      {
          return [
              'id' => $this->id,
              'full_address' => "{$this->address}, {$this->city}, {$this->postal_code}",
              'coordinates' => [
                  'lat' => $this->latitude,
                  'lng' => $this->longitude,
              ],
          ];
      }
      
  5. Testing Helpers:

    • Add helper methods to Address for testing:
      // app/Models/Address.php
      public static function createTestAddress($attributes = [])
      {
          return static::create(array_merge([
              'addressable_type' => 'App\Models\User',
              'addressable_id' => 1,
              'address' => 'Test Address',
              'city' => 'Test City',
              'postal_code' => '12345',
              'country' => 'Test Country',
          ], $attributes));
      }
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium