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

Kabupatenbundle Laravel Package

ais/kabupatenbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation Add the package to your Laravel project via Composer (note: this bundle is Symfony-based, so adaptation is required):

    composer require ais/kabupatenbundle:dev-master
    

    Since Laravel doesn’t use bundles, you’ll need to manually extract and adapt the bundle’s logic (e.g., Kabupaten entity, repository, and API routes) into Laravel’s Eloquent models, repositories, and route definitions.

  2. Extract Core Logic

    • Copy the Kabupaten entity (likely in Ais/KabupatenBundle/Entity/Kabupaten.php) into app/Models/Kabupaten.php.
    • Adapt the entity to use Laravel’s Eloquent ORM (e.g., replace Doctrine annotations with Laravel attributes or traits).
    • Example:
      // app/Models/Kabupaten.php
      namespace App\Models;
      use Illuminate\Database\Eloquent\Model;
      
      class Kabupaten extends Model
      {
          protected $table = 'kabupatens';
          protected $fillable = ['name', 'province_id', 'code'];
      }
      
  3. Set Up Database Run migrations to create the kabupatens table (adapt the schema from the bundle’s Doctrine migrations if needed):

    php artisan make:migration create_kabupatens_table
    

    Example migration:

    Schema::create('kabupatens', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('code')->unique();
        $table->unsignedBigInteger('province_id');
        $table->timestamps();
    });
    
  4. Seed Data Import the bundle’s sample data (e.g., from Ais/KabupatenBundle/Resources/data/kabupatens.csv) into your Laravel database:

    php artisan make:seeder KabupatenSeeder
    

    Example seeder:

    public function run()
    {
        $csv = Storage::disk('local')->get('path/to/kabupatens.csv');
        array_map('str_getcsv', explode("\n", $csv));
        // Process CSV and create Kabupaten records
    }
    
  5. First API Endpoint Create a controller to expose the data via RESTful routes:

    php artisan make:controller KabupatenController --api
    

    Example controller:

    // app/Http/Controllers/API/KabupatenController.php
    namespace App\Http\Controllers\API;
    use App\Models\Kabupaten;
    use App\Http\Controllers\Controller;
    
    class KabupatenController extends Controller
    {
        public function index()
        {
            return response()->json(Kabupaten::all());
        }
    }
    

    Add the route in routes/api.php:

    Route::get('/kabupatens', [\App\Http\Controllers\API\KabupatenController::class, 'index']);
    
  6. Test the API Visit http://your-app.test/api/kabupatens to fetch the list of kabupatens.


Implementation Patterns

Workflows

  1. Data Fetching and Filtering

    • Use Eloquent’s query builder to filter kabupatens by province or code:
      // Get kabupatens by province_id
      $kabupatens = Kabupaten::where('province_id', $provinceId)->get();
      
      // Search by name (partial match)
      $kabupatens = Kabupaten::where('name', 'like', '%search%')->get();
      
    • Pagination: Use Laravel’s pagination for large datasets:
      $kabupatens = Kabupaten::paginate(15);
      
  2. API Documentation

    • Since the bundle relies on NelmioApiDocBundle, manually document your Laravel API using tools like:
      • Laravel API Docs: darkaonline/l5-swagger.
      • Postman Collections: Export your routes to Postman for team sharing.
    • Example Swagger annotation (if using darkaonline/l5-swagger):
      /**
       * @OA\Get(
       *     path="/api/kabupatens",
       *     summary="Get all kabupatens",
       *     @OA\Response(response="200", description="List of kabupatens")
       * )
       */
      public function index()
      
  3. Integration with Forms

    • Use the kabupaten data in Laravel Blade forms or frontend frameworks (e.g., Vue/React):
      <!-- Example: Select province and kabupaten in a form -->
      <select name="province" id="province">
          @foreach($provinces as $province)
              <option value="{{ $province->id }}">{{ $province->name }}</option>
          @endforeach
      </select>
      
      <select name="kabupaten" id="kabupaten" disabled>
          <!-- Dynamically populated via JavaScript/AJAX -->
      </select>
      
      <script>
          $('#province').change(function() {
              const provinceId = $(this).val();
              $.get(`/api/kabupatens?province_id=${provinceId}`, function(kabupatens) {
                  $('#kabupaten').empty();
                  kabupatens.forEach(k => {
                      $('#kabupaten').append(`<option value="${k.id}">${k.name}</option>`);
                  });
                  $('#kabupaten').prop('disabled', false);
              });
          });
      </script>
      
  4. Validation

    • Validate kabupaten data using Laravel’s Form Requests:
      php artisan make:request StoreKabupatenRequest
      
      Example request:
      public function rules()
      {
          return [
              'name' => 'required|string|max:255',
              'code' => 'required|string|max:10|unique:kabupatens',
              'province_id' => 'required|exists:provinces,id',
          ];
      }
      
  5. Testing

    • Write unit tests for your KabupatenController and model:
      public function test_kabupatens_index()
      {
          $kabupatens = Kabupaten::factory()->count(3)->create();
          $response = $this->getJson('/api/kabupatens');
          $response->assertStatus(200)
                   ->assertJsonCount(3);
      }
      

Integration Tips

  • Provinces-Kabupatens Relationship: Create a Province model and establish a many-to-one relationship:

    // app/Models/Province.php
    public function kabupatens()
    {
        return $this->hasMany(Kabupaten::class);
    }
    
    // app/Models/Kabupaten.php
    public function province()
    {
        return $this->belongsTo(Province::class);
    }
    
  • Caching: Cache frequently accessed kabupaten lists to reduce database load:

    $kabupatens = Cache::remember('kabupatens_all', now()->addHours(1), function() {
        return Kabupaten::all();
    });
    
  • Localization: If kabupaten names are locale-specific, use Laravel’s localization features:

    // app/Models/Kabupaten.php
    public function getNameAttribute()
    {
        return __("kabupatens.{$this->code}");
    }
    

    Define translations in resources/lang/id/kabupatens.php:

    return [
        '3676' => 'Kota Bandung',
        '3671' => 'Bandung',
    ];
    

Gotchas and Tips

Pitfalls

  1. Symfony vs. Laravel Incompatibilities

    • Doctrine ORM: The bundle uses Doctrine, but Laravel uses Eloquent. Directly porting Doctrine entities may require adjustments (e.g., lifecycle callbacks, event listeners).
      • Fix: Replace Doctrine events with Eloquent model observers or accessors.
    • Routing: The bundle assumes Symfony’s routing system. Laravel’s routing is simpler but lacks some Symfony features (e.g., resource routing).
      • Fix: Manually define routes in routes/api.php or use Route::resource() for RESTful conventions.
  2. Missing Dependencies

    • The bundle requires NelmioApiDocBundle, FOSRestBundle, and JMSSerializerBundle, which are Symfony-specific. Laravel alternatives:
      • API Docs: Use darkaonline/l5-swagger or spatie/laravel-api-docs.
      • Serialization: Laravel’s built-in JSON serialization works out of the box.
      • Fix: Skip Symfony-specific bundles and use Laravel equivalents.
  3. Data Format Mismatches

    • The bundle’s CSV/data format may not align with Laravel’s expectations (e.g., column names, encodings).
      • Fix: Preprocess the data before seeding:
        $csv = Str::of(file_get_contents('path/to/kabupatens.csv'))
            ->replace([';',
        
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware