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 States Laravel Package

adrianmejias/laravel-states

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require adrianmejias/laravel-states:~1.0
    

    Add to config/app.php:

    'providers' => [
        AdrianMejias\States\StatesServiceProvider::class,
    ],
    'aliases' => [
        'States' => AdrianMejias\States\StatesFacade::class,
    ]
    
  2. Set Up Database:

    php artisan vendor:publish --provider="AdrianMejias\States\StatesServiceProvider"
    php artisan states:migration
    composer dump-autoload
    

    Run migrations and seed:

    php artisan migrate --seed
    
  3. First Use Case: Fetch a state by abbreviation:

    $state = States::getByAbbreviation('CA'); // Returns California data
    

    Or fetch all states:

    $allStates = States::all();
    

Implementation Patterns

Core Workflows

  1. Retrieving State Data:

    • By Abbreviation:
      $state = States::getByAbbreviation('NY'); // Returns state object
      
    • By Name:
      $state = States::getByName('Texas');
      
    • All States:
      $states = States::all(); // Returns collection of state objects
      
  2. Integration with Models: Add a relationship in your model (e.g., User):

    public function state()
    {
        return $this->belongsTo(State::class);
    }
    

    Use in queries:

    $usersInCalifornia = User::whereHas('state', function($query) {
        $query->where('abbreviation', 'CA');
    })->get();
    
  3. Form Validation: Validate state abbreviations in Form Requests:

    public function rules()
    {
        return [
            'state' => 'required|state_abbreviation',
        ];
    }
    

    (Requires adding the validation rule to AppServiceProvider or a custom rule.)

  4. Localization: Use state names in views:

    {{ States::getByAbbreviation($user->state)->name }}
    

Advanced Patterns

  • Custom State Queries:
    $states = States::where('region', 'West')->get();
    
  • Dynamic State Selection:
    $states = States::where('name', 'like', request('search').'%')->get();
    
  • API Responses:
    return response()->json(States::all()->toArray());
    

Gotchas and Tips

Pitfalls

  1. Laravel 5 Only:

    • This package only works with Laravel 5.x. Attempting to use it in Laravel 6+ will fail due to deprecated syntax (e.g., config/app.php structure, vendor:publish behavior).
  2. Database Dependencies:

    • The package requires a states table in your database. Skipping migrations/seeding will break functionality.
    • If you modify the table name via config, ensure the seeder and migration reflect the change.
  3. Validation Rule:

    • The state_abbreviation validation rule is not included by default. You must manually register it in AppServiceProvider:
      Validator::extend('state_abbreviation', function ($attribute, $value, $parameters, $validator) {
          return States::getByAbbreviation($value) !== null;
      });
      
  4. Archived Package:

    • No active maintenance. Use at your own risk for new projects. Consider alternatives like spatie/laravel-states for Laravel 6+.

Debugging Tips

  • Missing States?: Verify the states table exists and is populated. Check database/seeds/StatesSeeder.php for errors.

    php artisan db:seed --class=StatesSeeder
    
  • Facade Not Found: Ensure the States alias is correctly registered in config/app.php and the service provider is loaded.

  • Performance: Cache state collections if frequently accessed:

    $states = Cache::remember('all_states', now()->addHours(1), function() {
        return States::all();
    });
    

Extension Points

  1. Add Custom Fields: Extend the states table migration to include additional columns (e.g., timezone, population):

    Schema::table('states', function (Blueprint $table) {
        $table->string('timezone')->nullable();
    });
    

    Update the seeder to populate these fields.

  2. Support Non-US States: The package supports other countries via the country_code column. Add a new seeder or migration for additional regions.

  3. Custom Query Builder: Extend the State model to add scopes:

    public function scopeByRegion($query, $region)
    {
        return $query->where('region', $region);
    }
    

    Usage:

    $westernStates = State::byRegion('West')->get();
    
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat